简体   繁体   English

来自中间件的ASP.NET 5 DI注册

[英]ASP.NET 5 DI Registration From Middleware

I have a middleware class that gets the current user logged into the application from the database for the current request: 我有一个中间件类,该类可以将当前用户从数据库中登录到当前请求的应用程序中:

public class CurrentUserMiddleware
{
    RequestDelegate m_next;
    UserManager<User> m_userManager;

    public CurrentUserMiddleware(RequestDelegate next, UserManager<User> userManager )
    {
        m_next = next;
        m_userManager = userManager;
    }

    public async Task Invoke(HttpContext context)
    {
        var userId = context.User.Identity.GetUserId();
        var user = await m_userManager.FindByIdAsync(userId);

        var currentUserContext = new CurrentUserContext { User = user };

        // Register CurrentUserContext with DI to this currentUserContext instance

        await m_next(context);
    }
}

After this is resolved I want to register a CurrentUserContext that can be resolved in other areas of my application via DI. 解决此问题后,我想注册一个CurrentUserContext ,可以通过DI在我的应用程序的其他区域中解决该问题。

For example: 例如:

public class HomeController : Controller
{
    private readonly CurrentUserContext m_currentUserContext;

    public HomeController(CurrentUserContext currentUserContext)
    {
        m_currentUserContext = currentUserContext;
    }

    public async Task<IActionResult> Index()
    {
        var userName = m_currentUserContext.User.Username;
        return View();
    }
}

How do I properly register this CurrentUserContext ? 我如何正确注册此CurrentUserContext All other DI registrations are done in Startup ConfigureServices , however that doesn't work for this case since I need to resolve the CurrentUserContext on each request. 所有其他DI注册都在Startup ConfigureServices中完成,但是在这种情况下不起作用,因为我需要在每个请求上解析CurrentUserContext

Not sure what DI container you using, so a bit generic... 不确定您使用的是哪个DI容器,所以有点通用...

For most DI containers default instantiation is per-invocation, so irrespective where it registered at the moment of instantiation of the object you can access current context. 对于大多数DI容器,默认实例化是每次调用的,因此,无论在对象实例化时它在什么位置注册,您都可以访问当前上下文。 Most containers also provide an option to specify "factory" method instead of just type name - so you can just call your "Invoke" method from such factory. 大多数容器还提供了一个选项来指定“ factory”方法,而不仅仅是类型名称-因此您可以从此类工厂调用“ Invoke”方法。

Note that most containers don't support async resolution, so you can register objects that will give you access to you "user context" asyncronously: 请注意,大多数容器不支持async解析,因此您可以注册可以async访问“用户上下文”的对象:

 ICreateUserContext { Task<CurrentUserContext> GetContextAsync();}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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