简单的注射器:如何注入HttpContext的?注射器、简单、HttpContext

2023-09-05 23:16:45 作者:错过我的年华

我已经开始使用简单的注射器作为我的DI容器(主要是出于性能的原因:如果有人有意见,请让我知道),但一些类,我写使用HttpContextBase作为构造函数的参数。 我已经解决了,现在从构造函数中删除并创建一个属性,是这样的:

I have started using Simple Injector as my DI container (mostly for performance reason: if somebody has suggestions, please let me know) but some of the classes I wrote use HttpContextBase as constructor parameter. I have resolved for now removing it from the constructor and creating a Property, something like this:

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

但我不喜欢这种解决方案有何意见?

but I don't like this solution... any advices?

推荐答案

您应该总是青睐构造注射过任何东西。这几乎总是可能的。你可以注册 HttpContextBase 如下:

You should always favor constructor injection over anything else. This is almost always possible. You can register your HttpContextBase as follows:

container.RegisterPerWebRequest<HttpContextBase>(() =>
    new HttpContextWrapper(HttpContext.Current));

这可以在调用验证(),因为在应用程序启动 HttpContext.Current 是,当出现问题了 HttpContextWrapper 不允许传递空到构造函数。

This can cause a problem when calling Verify(), since during application startup HttpContext.Current is null, and HttpContextWrapper does not allow passing null into the constructor.

它总是好的尝试让您的配置可验证,您可以更改登记为以下内容:

It's always good to try to keep your configuration verifiable, and you can change that registration to the following:

// using SimpleInjector.Advanced;

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

FakeHttpContext 是一个空的 HttpContextBase 执行prevent返回的情况下,容器的检验。该 FakeHttpContext 很简单:

FakeHttpContext is an empty HttpContextBase implementation to prevent returning null in case the container is verifying. The FakeHttpContext is simply this:

public class FakeHttpContext : HttpContextBase { }