如何在DI中注册自定义UserStore和UserManager

Swe*_*ell 13 c# asp.net-core-mvc asp.net-identity-3 asp.net-core

这是我的设置:

public class ApplicationUser : IdentityUser<Guid>
{
}
public class ApplicationRole : IdentityRole<Guid>
{
}
public class ApplicationUserLogin : IdentityUserLogin<Guid>
{
}
public class ApplicationUserClaim : IdentityUserClaim<Guid>
{
}
public class ApplicationRoleClaim : IdentityRoleClaim<Guid>
{
}
Run Code Online (Sandbox Code Playgroud)

这是我的UserStore的定义

public class ApplicationUserStore : UserStore<ApplicationUser, ApplicationRole, MyContext, Guid>
{
    public ApplicationUserStore(MyContext context, IdentityErrorDescriber describer = null)
        : base(context, describer)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的UserManager的定义

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store, IOptions<IdentityOptions> optionsAccessor,
        IPasswordHasher<ApplicationUser> passwordHasher, IEnumerable<IUserValidator<ApplicationUser>> userValidators,
        IEnumerable<IPasswordValidator<ApplicationUser>> passwordValidators, ILookupNormalizer keyNormalizer,
        IdentityErrorDescriber errors, IEnumerable<IUserTokenProvider<ApplicationUser>> tokenProviders,
        ILoggerFactory logger, IHttpContextAccessor contextAccessor)
        : base(
            store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors,
            tokenProviders, logger, contextAccessor)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的DbContext的定义:

public class MyContext : IdentityDbContext<ApplicationUser, ApplicationRole, Guid>
{
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的Startup.cs

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<MyContext>(options => options.UseSqlServer(Configuration.Get("Data:DbConnection")));

        services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<MyContext, Guid>()
            .AddUserStore<ApplicationUserStore>()
            .AddRoleStore<ApplicationRoleStore>()
            .AddUserManager<ApplicationUserManager>()
            .AddRoleManager<ApplicationRoleManager>()
            .AddDefaultTokenProviders();

        var builder = new ContainerBuilder();
        builder.Populate(services);
        var container = builder.Build();
        return container.Resolve<IServiceProvider>();
    }
Run Code Online (Sandbox Code Playgroud)

此构造函数的依赖项将起作用:

public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
Run Code Online (Sandbox Code Playgroud)

这个不会:

public AccountController(ApplicationUserManager userManager, SignInManager<ApplicationUser> signInManager)
Run Code Online (Sandbox Code Playgroud)

任何人都知道我做错了什么?

Mat*_*rey 10

DI通常用于界面驱动开发; .AddUserManager<ApplicationUserManager>()指定实现UserManager<>,而不是服务接口.这意味着它仍然期望你得到UserManager<ApplicationUser>并且只能这样使用它; 它会给你一个ApplicationUserManager.

我假设您有其他想要在您的方法上使用的方法ApplicationUserManager.如果没有, 只需按照它的工作方式使用依赖构造函数,并享受界面驱动的开发.如果是这样,您有3个选择:

  1. 通过组合而不是继承来使用扩展.而不是继承UserManager<>,写作ApplicationUserManager包装类; 你可以将它包含在构造函数中.这应该为您提供所需的所有功能ApplicationUserManager.

  2. 将其原样添加到DI框架中.这并不像听起来那么困难,因为它UserManager<>本身没有真正的状态:

    services.AddScoped<ApplicationUserManager>();
    
    Run Code Online (Sandbox Code Playgroud)

    这里的缺点是你实际上有两个UserManager<>对象用于用户的范围; 结果可能会有一些效率低下的问题.从当前代码的状态来看,我认为不是.

  3. 将其写为扩展方法.如果您有许多依赖项而不仅仅是UserManager<>基本功能,那么这可能非常复杂.


Raf*_*aeu 5

我现在在ASP.NET Core 1.1上,此问题已得到修复。

我可以轻松实现自己的UserManager和UserStore,然后按以下步骤引导应用程序:

// identity models
services
    .AddIdentity<ApplicationUser, ApplicationRole>()
    .AddEntityFrameworkStores<ApplicationDbContext, Guid>()
    .AddUserManager<ApplicationUserManager>()
    .AddUserStore<ApplicationUserStore>()
    .AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)

并将UserManager和UserStore都注入到我的Controller中,没有任何问题:

public AccountController(
    IIdentityServerInteractionService interaction,
    IClientStore clientStore,
    IHttpContextAccessor httpContextAccessor,
    ApplicationUserManager userManager,
    SignInManager<ApplicationUser> signInManager,
    IEmailSender emailSender,
    ISmsSender smsSender,
    ILoggerFactory loggerFactory)
{
    _interaction = interaction;
    _userManager = userManager;
    _signInManager = signInManager;
    _emailSender = emailSender;
    _smsSender = smsSender;
    _logger = loggerFactory.CreateLogger<AccountController>();
    _account = new AccountService(_interaction, httpContextAccessor, clientStore);
}
Run Code Online (Sandbox Code Playgroud)