c# - 尝试将类型注册到 IoC 容器时,HttpContext.Current 为空

标签 c# asp.net-mvc dependency-injection asp.net-mvc-5 unity-container

我正在尝试在我的 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 种情况(HttpContextHttpContext.SessionHttpContext.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 a SessionStateAccessor wrapper around HttpContextBase 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/

相关文章:

c# - 如何提取数字的位值?

c# - AOP 与元编程

c# - 将 Web API 添加到现有 MVC Web 应用程序后出现 404 错误

c# - 具体 .Net 类的依赖注入(inject)

java - @PostConstruct 的顺序和继承

C#.net Web 请求在调用 Web API 时无法获取 404 自定义错误消息,但 postman 却可以

c# - InRequestScope 中的 Ninject 依赖项不会被释放

asp.net-mvc - 返回一个 View 模型类型与传递的不同的 mvc 操作

c# - 当我尝试添加图像时,MVC 总是返回 null

android - 如何注入(inject)动态创建的用例(android、整洁的架构、dagger2)