我们有一个依赖于 HttpContext
的类。
我们是这样实现的:
public SiteVariation() : this(new HttpContextWrapper(HttpContext.Current))
{
}
public SiteVariation(HttpContextBase context)
{}
现在我要做的是通过 Unity
实例化 SiteVariation
类,这样我们就可以创建一个构造函数。
但是我不知道如何以配置方式在 Unity 中配置这个新的 HttpContextWrapper(HttpContext.Current))
。
附言 这是我们使用的配置方式
<type type="Web.SaveRequest.ISaveRequestHelper, Common" mapTo="Web.SaveRequest.SaveRequestHelper, Common" />
最佳答案
Microsoft 已经围绕 .NET 中包含的 HttpContext
、HttpRequest
和 HttpResponse
构建了出色的包装器和抽象,因此我肯定会使用它们直接而不是自己包装。
您可以使用 InjectionFactory
为 HttpContextBase
配置 Unity,如下所示:
var container = new UnityContainer();
container.RegisterType<HttpContextBase>(new InjectionFactory(_ =>
new HttpContextWrapper(HttpContext.Current)));
此外,如果您需要HttpRequestBase
(我最常使用的)和HttpResponseBase
,您可以像这样注册它们:
container.RegisterType<HttpRequestBase>(new InjectionFactory(_ =>
new HttpRequestWrapper(HttpContext.Current.Request)));
container.RegisterType<HttpResponseBase>(new InjectionFactory(_ =>
new HttpResponseWrapper(HttpContext.Current.Response)));
您可以在单元测试中轻松模拟 HttpContextBase
、HttpRequestBase
和 HttpResponseBase
,而无需自定义包装器。
关于c# - 如何在Unity中实现这个(HttpContext)依赖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7968256/