Use DbContext in ASP .Net Singleton Injected Class

后端 未结 5 672
刺人心
刺人心 2020-11-29 01:10

I need to access my database in a Singleton class instantiated in my Startup class. It seems that injecting it directly results in a DbContext that is disposed.

I g

5条回答
  •  Happy的楠姐
    2020-11-29 01:53

    Original source: https://entityframeworkcore.com/knowledge-base/51939451/how-to-use-a-database-context-in-a-singleton-service-

    Since DbContext is scoped by default, you need to create scope to access it. It also allows you to handle its lifetime correctly - otherwise you'd keep instance of DbContext for a long time and this is not recommended.

    public class Singleton : ISingleton 
    {
    
        private readonly IServiceScopeFactory scopeFactory;
    
        public Singleton(IServiceScopeFactory scopeFactory)
        {
            this.scopeFactory = scopeFactory;
        }
    
        public void MyMethod() 
        {
            using(var scope = scopeFactory.CreateScope()) 
            {
                var db = scope.ServiceProvider.GetRequiredService();
    
                // when we exit the using block,
                // the IServiceScope will dispose itself 
                // and dispose all of the services that it resolved.
            }
        }
    }
    

提交回复
热议问题