与其他任何事情相比,您应该始终支持构造函数注入。这几乎总是可能的。您可以注册您的HttpContextBase
如下:
container.Register<HttpContextBase>(() =>
new HttpContextWrapper(HttpContext.Current),
Lifestyle.Scoped);
这可能会在调用时导致问题Verify()
,因为在应用程序启动期间HttpContext.Current
is null
, and HttpContextWrapper
不允许将 null 传递到构造函数中。
尝试一下总是好的保持您的配置可验证 https://simpleinjector.readthedocs.org/en/latest/howto.html#verify-the-containers-configuration,您可以将该注册更改为以下内容:
container.Register<HttpContextBase>(() =>
{
var context = HttpContext.Current;
if (context == null && container.IsVerifying) return new FakeHttpContext();
return new HttpContextWrapper(context);
},
Lifestyle.Scoped);
FakeHttpContext
是一个空的HttpContextBase
实施防止返回null
如果容器正在验证。这FakeHttpContext
就是这样:
public class FakeHttpContext : HttpContextBase { }
但请注意 HttpContext 是运行时数据并且在构造期间将运行时数据注入组件是一种反模式 https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=99。您应该创建一个特定于应用程序的抽象,为消费者提供其实际需要的内容(例如用户身份或租户 ID),而不是将 HttpContext 或对其进行任何抽象注入到组件中。这个抽象的实现可以简单地在内部调用 HttpContext.Current ,这完全不需要注入 HttpContext 。