How to implement a UserFactory using IHttpContextAccessor

后端 未结 1 752
终归单人心
终归单人心 2021-01-24 15:43

I used to have a UserFactory (before vNext) that used HttpContext.Current but since that is now gone I am having trouble recreating it.

I want

相关标签:
1条回答
  • 2021-01-24 16:11

    I suggest you make the UserFactory class non-static and register it as scoped:

    services.AddScoped<UserFactory>();
    

    This will create one instance per web request. You can inject this into every other class and let the UserFactory take a dependency on IHttpContextAccessor to get the current HttpContext.

    This adheres to the dependency inversion philosophy Microsoft is trying to implement in ASP.NET 5. Static classes do not really fit into this and should be avoided as much as possible.


    Example

    UserFactory class:

    public class UserFactory
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
    
        public UserFactory(IHttpContextAccessor httpContextAccessor) 
        {
            _httpContextAccessor = httpContextAccessor;
        }
    
        // other code...
    }
    

    ConfigureServices() in Startup class:

    public void ConfigureServices(IServiceCollection services)
    {
        // ...
    
        services.AddScoped<UserFactory>();
    
        // ...
    }
    

    Now you can inject an instance of UserFactory in a controller for example:

    public class SomeController : Controller
    {
        private readonly UserFactory _userFactory;  
    
        public SomeController(UserFactory userFactory)
        {
            _userFactory = userFactory;
        }
    
        // ...
    }
    

    Now when UserFactory is begin resolved, IHttpContextFactory inside UserFactory will also be resolved.

    0 讨论(0)
提交回复
热议问题