从 EF Core 中的部分类访问 DbContext

问题描述 投票:0回答:1

我正在构建一个 Hangfire 应用程序,并将数据库搭建到 EF Core。现在我创建了一个新的部分类,并且从该新部分中我想访问

DbContext
,这样我就可以做一些分类帐的事情。

但是DI似乎不起作用,有人有其他解决方案吗?

文件1

public partial class Config
{
    public string Name { get; set; }
    public string Value { get; set; }
    public string Description { get; set; }

    public bool IsUserManaged { get; set; }

    public string ConfigurationGroup { get; set; }

    public int CreatedBy { get; set; }
    public DateTime CreationTime { get; set; }
    public DateTime? LastModificationTime { get; set; }

    public int? LastModifiedBy { get; set; }
}

文件2

public partial class Config
{
    private IDbContextFactory<DataContext> _dataContext;
 
    public Config(IDbContextFactory<DataContext> dataContext)
    {
        _dataContext = dataContext
    }

    public static T GetConfigValue<T>(string key, T defaultValue, DataContext existingContext = null)
    {
        if (existingContext != null)
        {
            return GetConfigValue(existingContext, key, defaultValue);
        }
 
        return GetConfigValue(_dataContext, key, defaultValue);
    }

    public static T GetConfigValue<T>(DataContext ctx, string key)
    {
        return GetConfigValue(ctx, key, default(T));
    }

    public static T GetConfigValue<T>(DataContext ctx, string key, T defaultValue)
    {
        var value = GetRawConfigValue(ctx, key);
 
        if (String.IsNullOrEmpty(value)) 
            return defaultValue;

        try
        {
            var conv = TypeDescriptor.GetConverter(typeof(T));
            var item = (T)conv.ConvertFrom(null, CultureInfo.InvariantCulture, value);

            return item;
        }
        catch
        {
            return defaultValue;
        }
    }

    private static readonly Func<DataContext, string, string> GetRawConfigValue =
        (context, key) => (from c in context.Configs
                           where c.Name == key.ToString()
                           select c.Value).FirstOrDefault();
}

program.cs 中 DbContext 的初始化

builder.Services.AddDbContextFactory<DataContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

DI 确实适用于所有其他地方,但仅不适用于 EF Core 模型的部分类

c# asp.net-core dependency-injection entity-framework-core hangfire
1个回答
0
投票

依赖注入不适用于静态,您可以通过

using

创建一个实例
        public static T GetConfigValue<T>(string key, T defaultValue, DataContext existingContext = null)
        {
            ...

            using (var datacontext = new DataContext())
            {
                return GetConfigValue(dataContext, key, defaultValue);

            }
            
        }
© www.soinside.com 2019 - 2024. All rights reserved.