asp.net-mvc – mvc将httpcontext注入服务层

将httpContextBase注入我使用unity注入控制器的服务级别对象时,我遇到了一个大问题.

样品控制器

public HomeController : Controller{
    private IWorkContext _context;

    public HomeController(IWorkContext context){
        _context = context;
    }

}


public WorkContext : IWorkContext{

    private HttpContextBase _httpContext;

        public (HttpContextBase httpContext){
            _httpContext = httpContext;
        }

        public void DealWithCookies(){
            //do some thing with http context and deal with cookies
        }
    }

内部统一引导程序

container.RegisterType<HttpContextBase>().RegisterInstance(new HttpContextWrapper(HttpContext.Current) as HttpContextBase, new ContainerControlledLifetimeManager());

//With this line httpcontextbase is returned but as a singleton instead of new for each request.


   container.RegisterType<HttpContextBase>().RegisterInstance(new HttpContextWrapper(HttpContext.Current) as HttpContextBase, new PerRequestLifetimeManager());

//This line returns an exception 

类型HttpContextBase没有可访问的构造函数.

最佳答案 我根本不会注入HttpContext – 我会将它传递给每个方法调用:

public WorkContext : IWorkContext{

    private HttpContextBase _httpContext;

    public WorkContext(){
        ...
    }

    public void DealWithCookies(HttpContext ctx){
        //do some thing with http context and deal with cookies
    }
}

试图在这里使用依赖注入似乎是对我的原则的挪用.依赖注入允许您松散地耦合组件,但这里不需要它,因为您可以将上下文传递给方法并直接操作它.没有任何接口可以提供具体的实现,因此DI没有任何好处 – 它只是不必要的自举和“反模式”缺乏结构.

更不用说你无论如何都无法做到这一点,因为当你在应用程序启动时注册你的类型时,没有实例要注册(并且实例需要在每个请求上进行更改).

另外一点 – 我希望IWorkContext仅用于抽象cookie逻辑,而不是应用程序和数据层之间的层.如果没有,它根本不应该依赖于HTTP上下文.

点赞