繁体   English   中英

如何在UserManager和UserStore中使用DI

[英]How to use DI with UserManager and UserStore

给定一个MVC控制器构造函数的典型设置,它将UserManager (需要UserStore )传递给它的父类,如何将其转换为通过IoC注入?

从此开始:

public AccountController()
    : this(new UserManager<ApplicationUser>(
        new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
}

我会这样想:

public AccountController(IUserStore store)
    : this(new UserManager<ApplicationUser>(store)))
{
}

尽管这样做的确会丢失IdentityDbContext

应该如何设置IoC以及如何定义构造函数以允许注入UserManager,UserStore和IdentityDbContext?

您将需要创建一些类以简化注入。

让我们从UserStore开始。 创建所需的接口并使其继承自IUserStore<ApplicationUser>

public IUserStore : IUserStore<ApplicationUser> { }

创建一个如下的实现。

public ApplicationUserStore : UserStore<ApplicationUser>, IUserSTore {
    public ApplicationUserStore(ApplicationDbContext dbContext)
        :base(dbContext) { }
}

然后可以根据需要在OP中完成UserManager。

public class ApplicationUserManager : UserManager<ApplicationUser> {

    public ApplicationUserManager(IUserSTore userStore) : base(userStore) { }

}

因此,现在剩下的就是确保您决定使用哪个IoC容器注册必要的类。

ApplicationDbContext --> ApplicationDbContext 
IUserStore --> ApplicationUserStore 

如果您想更进一步并抽象化UserManager,则只需创建一个接口即可,该接口公开了您想要的功能

public interface IUserManager<TUser, TKey> : IDisposable
    where TUser : class, Microsoft.AspNet.Identity.IUser<TKey>
    where TKey : System.IEquatable<TKey> {
    //...include all the properties and methods to be exposed
    IQueryable<TUser> Users { get; }
    Task<TUser> FindByEmailAsync(string email);
    Task<TUser> FindByIdAsync(TKey userId);
    //...other code removed for brevity
}

public IUserManager<TUser> : IUserManager<TUser, string>
    where TUser : class, Microsoft.AspNet.Identity.IUser<string> { }

public IApplicationUserManager : IUserManager<ApplicationUser> { }

并请经理从中继承。

public class ApplicationUserManager : UserManager<ApplicationUser>, IApplicationUserManager {

    public ApplicationUserManager(IUserSTore userStore) : base(userStore) { }

}

现在,这意味着Controller现在可以依赖抽象而不是实现问题了

private readonly IApplicationUserManager userManager;

public AccountController(IApplicationUserManager userManager) {
    this.userManager = userManager;
}

再次在IoC容器中向实现注册接口。

IApplicationUserManager  --> ApplicationUserManager 

更新:

如果您喜欢冒险并且想要抽象身份框架本身,请查看此处给出答案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM