在ASP.NET Core MVC中注入ApplicationUser

时间:2017-04-10 11:53:31

标签: c# dependency-injection asp.net-core asp.net-core-mvc asp.net-core-identity

我有一个需要ApplicationUser的类(来自ASP.NET Identity)。该实例应该是当前用户。

public class SomeClass
{
    public SomeClass(ApplicationUser user)
    {

目前,我正在做的是从Controller中注入当前用户:

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

现在我想使用Microsoft提供的依赖注入。我无法弄清楚如何将ApplicationUser添加到服务中。它需要User这是Controller的一个属性。

那么如何通过Microsoft提供的DI注入ApplicationUser(当前用户的实例)?

1 个答案:

答案 0 :(得分:5)

您可以将UserManager<ApplicationUser>IHttpContextAccessor同时注入您班级的构造函数,然后:

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
    }
}

如果您不想直接依赖IHttpContextAccessor但仍希望使用DI,则可以创建界面来访问您的用户:

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);
    }
}

然后在DI容器中注册并注入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
    }
}

其他选项包括(如注释中所述)不注入任何内容但需要将ApplicationUser作为参数传递给需要它的方法(良好选项)并在使用具有特殊Initialize(user)方法的任何方法之前需要初始化(不太好,因为你无法确定在使用其他方法之前调用此方法)。