尝试将类型注册到IoC容器时,HttpContext.Current为null

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了尝试将类型注册到IoC容器时,HttpContext.Current为null相关的知识,希望对你有一定的参考价值。

我试图在我的ASP.NET MVC 5应用程序中设置IoC容器,以便我可以在我的应用程序中的任何位置访问这些对象。

我选择使用Unity.Mvc容器来完成这项工作。

在我的类型注册步骤中,我试图运行以下代码

var httpContext = new HttpContextWrapper(HttpContext.Current);
container.RegisterInstance<HttpContextBase>(httpContext);

var sessionWrapper = new HttpSessionStateWrapper(HttpContext.Current.Session);
container.RegisterInstance<HttpSessionStateBase>(sessionWrapper);

var httpServerUtility = new HttpServerUtilityWrapper(HttpContext.Current.Server);
container.RegisterInstance<HttpServerUtilityBase>(httpServerUtility);

但是,由于HttpContext.Current.Session对象为null,因此HttpContext.Current行抛出一个null异常。

如何正确地将非null HttpContextWrapper实例注入我的IoC容器?

答案

如何正确地将非null HttpContextWrapper实例注入我的IoC容器?

这些线涵盖了所有3个案例(HttpContextHttpContext.SessionHttpContext.Server):

var httpContext = new HttpContextWrapper(HttpContext.Current);
container.RegisterInstance<HttpContextBase>(httpContext);

由于在应用程序启动期间没有会话,因此您无法在MVC 5 Application Lifecycle中尽早访问它们。

httpContext注入组件后,可以在应用程序的运行时部分访问会话状态。

public class SomeService : ISomeService
{
    private readonly HttpContextBase httpContext;

    public SomeService(HttpContextBase httpContext)
    {
        if (httpContext == null)
            throw new ArgumentNullException(nameof(httpContext));
        this.httpContext = httpContext;
        // Session state is still null here...
    }

    public void DoSomething()
    {
        // At runtime session state is available.
        var session = httpContext.Session;
    }
}

注意:使服务直接依赖于会话状态通常不是一种好习惯。相反,您应该让控制器通过方法参数(即DoSomething(sessionValue))传递会话状态值,或者实现围绕SessionStateAccessorHttpContextBase包装器,它可以注入到您的服务中,类似于在ASP.NET Core中完成的方式。

以上是关于尝试将类型注册到IoC容器时,HttpContext.Current为null的主要内容,如果未能解决你的问题,请参考以下文章

IoC容器Autofac正篇之类型注册

String注解驱动开发如何按照条件向Spring容器中注册bean?这次我懂了!!

spring组件注册

面试官:Spring是如何把Bean注册到IOC容器中的?

spring利用注解来注册bean到容器

sping揭秘4某些无法注册到IOC容器的对象如何交给spring托管