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).
Init(context)) so that the consumers of the type are more aware of the actual needs. Injecting the context automatically behind the scenes by the DI will advance your DI skills but may lead to inconsistencies in the future.Init(context)you said may be an alternative, I wonder how do I enforce it to be called.