【问题标题】:Simple Injector: how to inject HttpContext?简单注入器:如何注入 HttpContext?
【发布时间】:2014-02-06 10:47:46
【问题描述】:

我已经开始使用 Simple Injector 作为我的 DI 容器(主要是出于性能原因:如果有人有建议,请告诉我)但是我编写的一些类使用 HttpContextBase 作为构造函数参数。 我已经解决了现在从构造函数中删除它并创建一个属性,如下所示:

    public HttpContextBase HttpContext
    {
        get
        {
            if (null == _httpContext)
                _httpContext = new HttpContextWrapper(System.Web.HttpContext.Current);
            return _httpContext;
        }
        set
        {
            _httpContext = value;
        }
    }

但我不喜欢这个解决方案...有什么建议吗?

【问题讨论】:

    标签: .net dependency-injection httpcontext simple-injector


    【解决方案1】:

    你应该总是喜欢构造函数注入而不是其他任何东西。这几乎总是可能的。您可以通过以下方式注册您的HttpContextBase

    container.Register<HttpContextBase>(() =>
        new HttpContextWrapper(HttpContext.Current), 
        Lifestyle.Scoped);
    

    这在调用Verify() 时可能会导致问题,因为在应用程序启动期间HttpContext.Currentnull,而HttpContextWrapper 不允许将null 传递给构造函数。

    尝试keep your configuration verifiable 总是好的,您可以将注册更改为以下内容:

    container.Register<HttpContextBase>(() =>
    {
        var context = HttpContext.Current;
        if (context == null && container.IsVerifying) return new FakeHttpContext();
        return new HttpContextWrapper(context);
    },
        Lifestyle.Scoped);
    

    FakeHttpContext 是一个空的HttpContextBase 实现,以防止在容器正在验证的情况下返回nullFakeHttpContext 就是这样:

    public class FakeHttpContext : HttpContextBase { }
    

    请注意,HttpContext 是运行时数据和injecting runtime data into components during construction is an anti-pattern。与其将 HttpContext 或其上的任何抽象注入到您的组件中,不如创建一个特定于应用程序的抽象,为消费者提供其实际需要的内容(例如用户身份或租户 ID)。这种抽象的实现可以简单地在内部调用 HttpContext.Current,这完全避免了注入 HttpContext 的需要。

    【讨论】:

    • 你有 Api.dll 和 Domain.dll。在 Domain.dll 中。有一个存储库,它需要你从 http 上下文中获取一个令牌来调用一些微服务并将令牌传递给它。您只能从 Http Context 获取令牌。创建存储库时,您必须在 Scope 中设置此令牌。特定于应用程序的抽象如何在这里提供帮助?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    相关资源
    最近更新 更多