尝试将类型注册到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个案例(HttpContext
,HttpContext.Session
和HttpContext.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)
)传递会话状态值,或者实现围绕SessionStateAccessor
的HttpContextBase
包装器,它可以注入到您的服务中,类似于在ASP.NET Core中完成的方式。
以上是关于尝试将类型注册到IoC容器时,HttpContext.Current为null的主要内容,如果未能解决你的问题,请参考以下文章