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??
DbContext
should be a singleton? - vasily.sibwhy scoped instead of transient
? During a web request, if the code requests the same context multiple times, it would make sense to cache all objects and changes until the end of the request, and persist them just once with a single call toSaveChanges
at the very end. This would perform better than eg 4 methods during the same request, creating a new CustomersContext context to retrieve and modify the same customer, and then save the changes 4 times, potentially overwriting each other's changes - Panagiotis Kanavos