Ошибка Unable to resolve service for type 'EntityFrameworkCore.DbContext' while attempting to activate
появилась ошибка:
Microsoft.AspNetCore.Identity.SecurityStampValidator [PlayVersus.Models.User]': Unable to resolve service for type 'Microsoft.EntityFrameworkCore.DbContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`
при добавлении в существующий Web Api Identity.
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextFactory<DataBaseContext>(opt => opt.UseNpgsql(DataBaseContext.GetConnectionSting()));
services.AddSingleton(typeof(IDbRepository<>), typeof(DbRepository<>));
services.AddControllers();
services.AddIdentityCore<IdentityUser>(options =>
{
options.User.RequireUniqueEmail = true;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
}).AddRoles<IdentityRole>().AddEntityFrameworkStores<DataBaseContext>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(
opt =>
{
opt.RequireHttpsMetadata = false;
opt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = AuthToken.ISSUER,
ValidateAudience = true,
ValidAudience = AuthToken.AUDIENCE,
ValidateLifetime = true,
IssuerSigningKey = AuthToken.GetSymmetricSecurityKey(),
ValidateIssuerSigningKey = true,
ClockSkew = TimeSpan.Zero
};
}
);
}
DataBaseContext:
public class DataBaseContext :IdentityDbContext, IDisposable {
public override DbSet<User> Users { get; set; }
public DbSet<IdentityRole> IdentityRoles { get; set; }
public DbSet<Discipline> Disciplines { get; set; }
public DbSet<Platform> Platforms { get; set; }
public DataBaseContext(DbContextOptions<DataBaseContext> options) : base(options)
{
}
public static string GetConnectionSting()
{
return new NpgsqlConnectionStringBuilder
{
Host = "localhost",
Port = 5432,
Database = "xxxxxxxx",
Username = "xxxxxx",
Password = "******",
Timeout = 300
}.ConnectionString;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>().ToTable("User").HasKey(c=>c.Id);
modelBuilder.Entity<Platform>().ToTable("Platforms");
modelBuilder.Entity<Discipline>().HasKey(c => c.TournamentID);
}
}
Возможна ли проблема, что я использую Postgres?
P.S. Перепробовал кучу советов и на github и на Stackoverflov(en/ru)?
Ответы (1 шт):
Ошибка заключалась в том, что я использовал AddDbContextFactory и AddIdentityCore одновременно при этом не совпадал жизненный цикл у AddDbContextFactory - Singleton, AddIdentityCore - Scoped. Добавив строку:
services.AddScoped<ApplicationDbContext>(p => p.GetRequiredService<IDbContextFactory<ApplicationDbContext>>().CreateDbContext());
Исходный ответ тут: https://stackoverflow.com/questions/66618830/identity-stores-with-db-context-factory