简体   繁体   中英

Inject ApplicationUser in ASP.NET Core MVC

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?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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