Home > Software engineering >  ServiceProviderExtensions GetRequiredService<DatabaseContext> to IdentityDbConext
ServiceProviderExtensions GetRequiredService<DatabaseContext> to IdentityDbConext

Time:04-14

I have a problem in .NET core 6. I need my serviceProvider to convert a custom DatabaseContext to an IdentityDbContext.

I have a similiar situation in project A, where it works. In project B it does not work

project A:

public class DatabaseContext : DbContext //DbContext is of Microsoft.EntityFrameworkCore

in Program.cs

services.TryAddScoped<DbContext>(sp => sp.GetRequiredService<DatabaseContext>());

works.

project B:

public class DatabaseContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>, ApplicationUserRole, IdentityUserLogin<string>, IdentityRoleClaim<string>, IdentityUserToken<string>> //AspNetCore.Identity.EntityFrameworkCore

in Program.cs

services.TryAddScoped<IdentityDbContext>(sp => sp.GetRequiredService<DatabaseContext>()); //services is of IServiceCollection

leads to Error:

Cannot implicitly convert type 'DatabaseContext' to Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityDbContext'

Why is it possible to convert DatabaseContext of project A to DbContext, but not possible to convert DatabaseContext to IdentityDbContext in project B?

I want to use the service in a nuget package, which I created by myself. A workaround that works, but is ugly as hell, is to include the code of the package in the main project and don't use IdentityDbContext in it but directly the custom DatabaseContext.

CodePudding user response:

IdentityDbContext<TUser,TRole,TKey,TUserClaim,TUserRole,TUserLogin,TRoleClaim,TUserToken> class inherits from IdentityUserContext<TUser,TKey,TUserClaim,TUserLogin,TUserToken> which inherits from DbContext directly:

public abstract class IdentityUserContext<TUser,TKey,TUserClaim,TUserLogin,TUserToken> : Microsoft.EntityFrameworkCore.DbContext ...

So ProjectB.DatabaseContext is not an IdentityDbContext.

  • Related