Implement ApplicationUser in ASP.NET Core MVC

I have a class that requires ApplicationUser (from an ASP.NET identifier). The instance must be the current user.

 public class SomeClass { public SomeClass(ApplicationUser user) { 

I am currently doing that I am entering the current user from the controller:

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

Now I want to use the dependency injection provided by Microsoft. I can’t understand how I can add ApplicationUser to services. This requires User , which is a property of the controller.

So, how do you enter ApplicationUser (current user instance) through the DI provided by Microsoft?

+6
source share
2 answers

You can embed both UserManager<ApplicationUser> and IHttpContextAccessor in the constructor of your class, and 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 do not want to take a direct dependency on IHttpContextAccessor , but still want to use DI, you can create an 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 the DI container and type in 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 the comments) not to insert anything, but require passing ApplicationUser as an argument to methods that require it (a good option), and require initialization before using any methods with the special Initialize(user) method (not so good, because that you cannot be sure that this method is called before using other methods).

+4
source

I'm new to Core, but the solution worked fine when I developed the correct way to add a service for the IApplicationUserAccessor interface:

 services.AddTransient<IApplicationUserAccessor, ApplicationUserAccessor>(); 
0
source

Source: https://habr.com/ru/post/1266550/


All Articles