在依赖注入系统之外创建一个UserManager

13

这是使用ASP.NET Core、Identity和Entity Framework Core实现的。我正在开发一个SaaS应用程序,其中有一个单独的管理员Web应用程序,您可以在该应用程序中向系统添加新的租户。在创建租户后,应用程序会为其创建一个默认数据库(每个租户设置一个数据库)。我想向此新数据库添加一个默认用户,但我在创建用户管理器时遇到了困难,因为我想在依赖注入系统之外创建它。

管理员Web应用程序使用startup.cs中创建的usermanager(通过内置的DI系统)作为管理员应用程序的管理器。当我尝试将用户添加到新的租户数据库时,我没有使用DI系统,我只想使用与新的租户数据库连接字符串相关联的IdentityDbContext创建一个UserManager。

在管理员应用程序中创建新租户后,我正在使用以下代码:

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>(.........
    }
}

UserManager的构造参数包含一些我无法找到哪些实例应该使用的示例。其中一些接口似乎具有默认实现,但我不确定这是否是继续进行(或传递空值)的方法。构造函数为:

    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)

从身份来源来看,似乎我可以为这些参数中的一些传递null,但我想确保我理解这里正在发生什么,以便我不会做任何错误的事情。

用户管理器的源代码在这里: https://github.com/aspnet/Identity/blob/dev/src/Microsoft.AspNetCore.Identity/UserManager.cs

谢谢, Brian

3个回答

7
在查看身份来源后,您可以传入null以获取正确的结果。应该先尝试这个方法。

3
以这种方式解决问题。
static IUserStore<ApplicationUser> _store = new UserStore<ApplicationUser>(new context()); 
static UserManager<ApplicationUser> _userManager = new UserManager<ApplicationUser>(_store, null, new PasswordHasher<ApplicationUser>(), null, null, null, null, null, null);

0

我认为您至少应该有UserStore:

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

我模拟了记录器。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接