如何在UserManager和UserStore中使用DI

时间:2017-01-26 21:52:07

标签: c# asp.net-web-api dependency-injection asp.net-identity inversion-of-control

给定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?

1 个答案:

答案 0 :(得分:3)

您需要创建一些类以便于注入。

让我们从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 

更新:

如果您有冒险精神并希望抽象身份框架本身,请查看answer given here

相关问题