C# 如何将DI与UserManager和UserStore一起使用

C# 如何将DI与UserManager和UserStore一起使用,c#,asp.net-web-api,dependency-injection,asp.net-identity,inversion-of-control,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()))) { } publiccountcontrol

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

从这一点开始:

public AccountController()
    : this(new UserManager<ApplicationUser>(
        new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
}
publiccountcontroller()
:此(新用户管理器)(
新的用户存储(新的ApplicationDbContext()))
{
}
我会这样想:

public AccountController(IUserStore store)
    : this(new UserManager<ApplicationUser>(store)))
{
}
公共帐户控制器(IUserStore)
:此(新用户管理器(存储)))
{
}
当然,这会丢失
IdentityDbContext


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

您需要创建一些类,以便更容易地注入


让我们从UserStore开始。创建所需的接口并将其从
IUserStore

继承这将有助于:嘿,太好了-谢谢!然后如何从
ApplicationUserManager
访问
DbContext
public IUserStore : IUserStore<ApplicationUser> { }
public ApplicationUserStore : UserStore<ApplicationUser>, IUserSTore {
    public ApplicationUserStore(ApplicationDbContext dbContext)
        :base(dbContext) { }
}
public class ApplicationUserManager : UserManager<ApplicationUser> {

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

}
ApplicationDbContext --> ApplicationDbContext 
IUserStore --> ApplicationUserStore 
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) { }

}
private readonly IApplicationUserManager userManager;

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