Use DbContext in ASP .Net Singleton Injected Class

后端 未结 5 653
刺人心
刺人心 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 02:05

    Update

    I'm fully aware that this solution is not the right way to do it. Please don't do what I did here all those years ago. In fact, don't inject a singleton DbContext at all.

    Old answer

    The solution was to call AddSingleton with my class being instantiated in the method parameter in my Startup class:

    services.AddSingleton(s => new FunClass(new MyContext(null, Configuration["Data:DefaultConnection:ConnectionString"])));
    

    The solution was to change my DbContext class:

    public class MyContext : IdentityDbContext
    {
        private string connectionString;
    
        public MyContext()
        {
            
        }
    
        public MyContext(DbContextOptions options, string connectionString)
        {
            this.connectionString = connectionString;
        }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            // Used when instantiating db context outside IoC 
            if (connectionString != null)
            {
                var config = connectionString;
                optionsBuilder.UseSqlServer(config);
            }
         
            base.OnConfiguring(optionsBuilder);
        }
    
    }
    

    As multiple people have however warned, using a DbContext in a singleton class might be a very bad idea. My usage is very limited in the real code (not the example FunClass), but I think if you are doing this it would be better to find other ways.

提交回复
热议问题