Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 526
dpp Avatar asked Apr 10 '17 11:04

dpp


1 Answers

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

like image 120
Evk Avatar answered Nov 15 '22 06:11

Evk