How to use DI with UserManager and UserStore

浪尽此生 提交于 2019-12-01 19:05:02
Nkosi

You would need to create some classes to allow for easier injection.

Let us start with the UserStore. Create the desired interface and have it inherit from IUserStore<ApplicationUser>

public IUserStore : IUserStore<ApplicationUser> { }

Create an implementation as follows.

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

The UserManager can then be done as desired in the OP.

public class ApplicationUserManager : UserManager<ApplicationUser> {

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

}

SO now all that is left is to make sure that which ever IoC container you decide to use registers the necessary classes.

ApplicationDbContext --> ApplicationDbContext 
IUserStore --> ApplicationUserStore 

If you want to go a step further and abstract the UserManager then just create an interface that exposes the functionality you want

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> { }

and have you manager inherit from that.

public class ApplicationUserManager : UserManager<ApplicationUser>, IApplicationUserManager {

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

}

This now means that the Controller can now depend on an abstraction and not on implementation concerns

private readonly IApplicationUserManager userManager;

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

And again you register the interface with the implementation in the IoC container.

IApplicationUserManager  --> ApplicationUserManager 

UPDATE:

If you are feeling adventurous and want to abstract identity framework itself take a look at the answer given here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!