Use DbContext in ASP .Net Singleton Injected Class

后端 未结 5 694
刺人心
刺人心 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条回答
  •  星月不相逢
    2020-11-29 01:50

    The reason it doesn't work is because the .AddDbContext extension is adding it as scoped per request. Scoped per request is generally what you want and typically save changes would be called once per request and then the dbcontext would be disposed at the end of the request.

    If you really need to use a dbContext inside a singleton, then your FunClass class should probably take a dependency on IServiceProvider and DbContextOptions instead of directly taking a dependency on the DbContext, that way you can create it yourself.

    public class FunClass
    {
        private GMBaseContext db;
    
        public FunClass(IServiceProvider services, DbContextOptions dbOptions) 
        {
            db = new GMBaseContext(services, dbOptions);
        }
    
        public List GetUsers()
        {
             var lst = db.Users.Select(c=>c.UserName).ToList();
            return lst;
        }
    }
    

    That said, my advice would be to carefully consider whether you really need your FunClass to be a singleton, I would avoid that unless you have a very good reason for making it a singleton.

提交回复
热议问题