Creating a UserManager outside the built-in dependency injection system

This is the use of the asp.net core with the core identity structure and entity. I am working on a saas application where I have a separate administration application where you can add new tenants to the system. After creating a tenant, the application creates a default database (database for each tenant) for the new tenant. I want to add a default user to this new database, but I'm struggling with creating a user manager outside of the dependency injection system.

The admin web application uses usermanager, which is created in startup.cs (via the built-in DI system) as a manager for the admin application. When I go to add a user to a new tenant database, I do not use the DI system. I just want to create a UserManager with an IdentityDbContext associated with the connection string for the new tenant database.

I use this after creating a new tenant in the admin application:

public class TenantDbInitializer { private Tenant tenant; private ApplicationDbContext context; private UserManager<ApplicationUser> userManager; public TenantDbInitializer(Tenant tenant) { this.tenant = tenant; } public void Init() { // tenant contains connection string context = new ApplicationDbContext(tenant); var userStore = new UserStore<ApplicationUser>(context); userManager = new UserManager<ApplicationUser>(......... } } 

The parameters of the UserManager construct contain elements that I cannot find in the examples in which instances I should use. Some interfaces seem to have default implementations, but I'm not sure if this is a way to continue (or to pass null). Constructor:

  public UserManager(IUserStore<TUser> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<TUser> passwordHasher, IEnumerable<IUserValidator<TUser>> userValidators, IEnumerable<IPasswordValidator<TUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<TUser>> logger) 

Looking at the source of the identity, it seems that I can pass null for some of these parameters, but I want to make sure that I understand what is happening here, so I am not doing anything wrong.

Source for user manager: https://github.com/aspnet/Identity/blob/dev/src/Microsoft.AspNetCore.Identity/UserManager.cs

Thanks Brian

+9
source share
2 answers

After looking at the identification source, you can pass zeros to get the correct results. Should have tried it first.

+7
source

I think you should have at least a UserStore:

  UserStore<ApplicationUser> _userStore = new UserStore<ApplicationUser>(context, null); Mock<ILogger<UserManager<ApplicationUser>>> mockLogger = null; mockLogger = new Mock<ILogger<UserManager<ApplicationUser>>>(); 

I mocked the receptionist.

0
source

All Articles