Why is services.AddDbContext() makes dbContext as a Scoped service?Shoudln't be a Singleton service?

asp.net-core c# entity-framework entity-framework-core

Question

I am using ASP.NET Core 2.2 with Pomelo.EntityFramework.MySql.

Here is my code:

 services.AddDbContext<dbContext>(options => options.UseMySQL(appConfigsSection["DbConnectionString"]));
 services.AddSingleton<IUserService, UserService>();


 services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x=> {
                x.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();       
                    }
                };

Here is the error:

asp.net core Cannot consume scoped service from singleton

on the line of:

 var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>(); 

My understanding is the DBContext should be used as a Singleton service, so is the IUserService. But it seems that DBContext is treated as a Scoped Service.

I can easily fix it by switching my IUserService back to Scoped Service. But I am wondering why can't I use DBContext as a Single service?

I think the DBContext should be used as a Singleton service, correct??

here

1
0
4/17/2019 7:25:16 AM

Popular Answer

DbContext should not be used as a singleton because it is holding a connection object which cannot be used by multiple threads at the same time. You will run into errors if two requests try to use it at the same time. If your service depends on the context, the service cannot be a singleton.

Scoped makes sense since it allows for you to pass around DB objects between services and get the same DbContext in all of them so you can query entities in one service and save the changes in another.

You can change it to transient if you need to run queries in parallel in two services for example. The service lifetime is a parameter on AddDbContext().

5
4/17/2019 7:28:41 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow