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??