我正在尝试在我的 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
行抛出空异常,因为 HttpContext.Current
对象为 null。
如何正确地将非空 HttpContextWrapper
实例注入(inject)到我的 IoC 容器中?
最佳答案
How can I correctly inject a non-null HttpContextWrapper instance into my IoC container?
这些行涵盖了所有 3 种情况(HttpContext
、HttpContext.Session
和 HttpContext.Server
):
var httpContext = new HttpContextWrapper(HttpContext.Current);
container.RegisterInstance<HttpContextBase>(httpContext);
由于在应用程序启动期间没有 session ,因此您无法在 MVC 5 Application Lifecycle 中尽早访问它们.
将 httpContext
注入(inject)组件后,您可以在应用程序的运行时 部分访问 session 状态。
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;
}
}
NOTE: It is generally not a good practice to make your services depend directly on session state. Instead, you should have the controller pass session state values through method parameters (i.e.
DoSomething(sessionValue)
), or alternatively implement aSessionStateAccessor
wrapper aroundHttpContextBase
that can be injected into your services, similar to how it is done in ASP.NET Core.
关于c# - 尝试将类型注册到 IoC 容器时,HttpContext.Current 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49033201/