Inject ApplicationUser in ASP.NET Core MVC

◇◆丶佛笑我妖孽 提交于 2020-12-08 07:29:24

问题


I have a class that requires ApplicationUser (from ASP.NET Identity). The instance should be the current user.

public class SomeClass
{
    public SomeClass(ApplicationUser user)
    {

Currently, what I'm doing is I inject the current user from the Controller:

var currentUser = await _userManager.GetUserAsync(User);
var instance = new SomeClass(currentUser);

Now I want to use Dependency Injection provided by Microsoft. I can't figure out how am I going to add ApplicationUser to the services. It requires User which is a property of the Controller.

So how do you inject ApplicationUser (instance of the current user) via DI provided by Microsoft?


回答1:


You can inject both UserManager<ApplicationUser> and IHttpContextAccessor to the constructor of your class, then:

public class SomeClass
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly IHttpContextAccessor _context;
    public SomeClass(UserManager<ApplicationUser> userManager,IHttpContextAccessor context)
    {
        _userManager = userManager;
        _context = context;
    }

    public async Task DoSomethingWithUser() {
        var user = await _userManager.GetUserAsync(_context.HttpContext.User);
        // do stuff
    }
}

If you don't want to take direct dependency on IHttpContextAccessor but still want to use DI, you can create interface to access your user:

public interface IApplicationUserAccessor {
    Task<ApplicationUser> GetUser();
}

public class ApplicationUserAccessor : IApplicationUserAccessor {
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly IHttpContextAccessor _context;
    public ApplicationUserAccessor(UserManager<ApplicationUser> userManager, IHttpContextAccessor context) {
        _userManager = userManager;
        _context = context;
    }

    public Task<ApplicationUser> GetUser() {
        return _userManager.GetUserAsync(_context.HttpContext.User);
    }
}

Then register it in DI container and inject into SomeClass:

public class SomeClass
{
    private readonly IApplicationUserAccessor _userAccessor;
    public SomeClass(IApplicationUserAccessor userAccessor)
    {
        _userAcccessor = userAccessor;
    }

    public async Task DoSomethingWithUser() {
        var user = await _userAccessor.GetUser();
        // do stuff
    }
}

Other options include (as mentioned in comments) not inject anything but require passing ApplicationUser as argument to the methods which require it (good option) and require initialization before using any methods with special Initialize(user) method (not so good, because you cannot be sure this method is called before using other methods).



来源:https://stackoverflow.com/questions/43322447/inject-applicationuser-in-asp-net-core-mvc

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