No service for type Identity.UserManager when using multiple identity users
Ideally you would call the same identity setup for the derived user types as for the base user type.
Unfortunately AddIdentity
method contains some code that prevents of using it more than once.
Instead, you could use AddIdentityCore
. The role services are already registered by the AddIdentity
, the only difference is that AddIdentityCore
registers UserClaimsPrincipalFactory<TUser>
, so in order to match AddIdentity
setup it needs to be replaced with UserClaimsPrincipalFactory<TUser, TRole>
via AddClaimsPrincipalFactory
method.
The code looks like something like this:
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders()
.AddDefaultUI();
services.AddIdentityCore<StudentUser>()
.AddRoles<IdentityRole>()
.AddClaimsPrincipalFactory<UserClaimsPrincipalFactory<StudentUser, IdentityRole>>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders()
.AddDefaultUI();
services.AddIdentityCore<EmployeeUser>()
.AddRoles<IdentityRole>()
.AddClaimsPrincipalFactory<UserClaimsPrincipalFactory<EmployeeUser, IdentityRole>>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders()
.AddDefaultUI();
Of course you could move the common parts in a custom extension methods.
Update: Although the role services are already configured, you still need to call AddRoles
in order to set correctly the Role
property of the IndentityBuilder
, which then is used by the AddEntityFrameworkStores
.
Tested on fresh project:
dotnet new mvc --auth Individual
Startup.cshtml
services.AddDefaultIdentity<User>()
.AddEntityFrameworkStores<ApplicationDbContext>();
User.cs
public class User : IdentityUser
{
public string Test { get; set; }
}
Probably here's your problem:
_LoginPartial.cshtml
@inject SignInManager<User> SignInManager
@inject UserManager<User> UserManager
Also tested this way:
Startup.cs
services.AddDefaultIdentity<User2>()
.AddEntityFrameworkStores<ApplicationDbContext>();
Users.cs
public class User : IdentityUser
{
public string TestA { get; set; }
}
public class User2 : User
{
public string TestB { get; set; }
}
_LoginPartial.cshtml
@inject SignInManager<User2> SignInManager
@inject UserManager<User2> UserManager