How to implement a UserFactory using IHttpContextAccessor

别说谁变了你拦得住时间么 提交于 2020-02-16 05:13:27

问题


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 it to be a static class that sets and gets the current user to access user data throughout the application.

I know I must use the DI system but not sure how.

Code so far:

public class CurrentContext : IHttpContextAccessor
    {
        private IHttpContextAccessor ctx;

        public HttpContext HttpContext
        {
            get
            {
                return ctx.HttpContext;
            }

            set
            {
                ctx.HttpContext = value;
            }
        }
    }


services.AddTransient<IHttpContextAccessor, CurrentContext>();

    public class UserFactory
    {
        private IHttpContextAccessor _context;

        public UserFactory(IHttpContextAccessor Context)
        {
            _context = Context;
        }

        public void Add(string s) => _context.HttpContext.Session.SetString(s, s);

        public string Get(string s) => _context.HttpContext.Session.GetString(s);
}

How can I get a UserFactory instance anywhere in my app with the current context?


回答1:


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.



来源:https://stackoverflow.com/questions/32316180/how-to-implement-a-userfactory-using-ihttpcontextaccessor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!