EF 7(核心)。像AddTransient一样创建DBContext

时间:2016-01-22 16:59:12

标签: c# asp.net-core asp.net-core-mvc entity-framework-core

根据我在下面配置DbContext时的文档,DI在范围内注册(每个http请求)

services.AddEntityFramework()
   .AddSqlServer()
   .AddDbContext<DBData>(options => {
        options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]);                    
    }
);

当我尝试在另一个线程中访问它时,会出现问题。

public class HomeController : Controller
{
    private readonly DBData _context;

    public HomeController(DBData context)
    {
        _context = context;
    }

    public IActionResult StartInBackground()
    {
        Task.Run(() =>
            {
                Thread.Sleep(3000);
                //System.ObjectDisposedException here
                var res = _context.Users.FirstOrDefault(x => x.Id == 1);
            });

        return View();
    }
}

我想为每次调用配置DbContext创建(AddTransition)。它会让我有可能编写下一个代码

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<DBData>(options => {
                //somehow configure it to use AddTransient
                options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]);                    
                }
            );

        services.AddTransient<IUnitOfWorkFactoryPerCall, UnitOfWorkFactory>();
        services.AddScoped<IUnitOfWorkFactoryPerRequest, UnitOfWorkFactory>();

        services.AddMvc();
    }

    public interface IUnitOfWorkFactoryPerCall : IUnitOfWorkFactory { }
    public interface IUnitOfWorkFactoryPerRequest : IUnitOfWorkFactory { }

    public interface IUnitOfWorkFactory : IDisposable
    {
       DBData Context { get; }
    }

    public class UnitOfWorkFactory : IUnitOfWorkFactoryPerCall, IUnitOfWorkFactoryPerRequest
    {
        public UnitOfWorkFactory(DBData context)
        {
            Context = context;
        }

        public DBData Context
        {
            get; private set;
        }

        public void Dispose()
        {
            Context.Dispose();
        }
    }

所以现在如果我想为每个请求创建DBContext,我将使用IUnitOfWorkFactoryPerRequest,当我想在某个后台线程中使用DBContext时,我可以使用IUnitOfWorkFactoryPerCall

2 个答案:

答案 0 :(得分:0)

我的临时解决方案。 我创建了单例,它可以以瞬态方式创建上下文&#34;

app/

然后我在Startup Configure方法中调用init方法

public class AppDependencyResolver
{
    private static AppDependencyResolver _resolver;

    public static AppDependencyResolver Current
    {
        get
        {
            if (_resolver == null)
                throw new Exception("AppDependencyResolver not initialized. You should initialize it in Startup class");
            return _resolver;
        }
    }

    public static void Init(IServiceProvider services)
    {
        _resolver = new AppDependencyResolver(services);
    }

    private readonly IServiceProvider _serviceProvider;

    public AppDependencyResolver(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public IUnitOfWorkFactory CreateUoWinCurrentThread()
    {
        var scopeResolver = _serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope();
        return new UnitOfWorkFactory(scopeResolver.ServiceProvider.GetRequiredService<DBData>(), scopeResolver);
    }
}

毕竟我可以在某个后台话题中调用public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { AppDependencyResolver.Init(app.ApplicationServices); //other configure code }

如果有人能提供更优雅的解决方案,我将不胜感激。

答案 1 :(得分:-1)

在您的控制器中,您为什么要注入private readonly DBData _context;?如果您已经通过DI注册了IUnitOfWorkFactoryPerCall,我应该将其注入您的控制器吗?然后,您可以通过界面访问您的上下文。

要扩展,我建议您这样做:

public class HomeController : Controller
{
    private readonly IUnitOfWorkFactoryPerCall _contextFactory;

    public HomeController(IUnitOfWorkFactoryPerCall contextFactory)
    {
        _contextFactory = contextFactory;
    }

    public IActionResult StartInBackground()
    {
        Task.Run(() =>
            {
                Thread.Sleep(3000);
                //System.ObjectDisposedException here
                var res = _contextFactory.Context.Users.FirstOrDefault(x => x.Id == 1);
            });

        return View();
    }
}