c# - 如何在Unity中实现这个(HttpContext)依赖?

标签 c# asp.net inversion-of-control unity-container httpcontext

我们有一个依赖于 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 中包含的 HttpContextHttpRequestHttpResponse 构建了出色的包装器和抽象,因此我肯定会使用它们直接而不是自己包装。

您可以使用 InjectionFactoryHttpContextBase 配置 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)));

您可以在单元测试中轻松模拟 HttpContextBaseHttpRequestBaseHttpResponseBase,而无需自定义包装器。

关于c# - 如何在Unity中实现这个(HttpContext)依赖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7968256/

相关文章:

inversion-of-control - 将结构映射与 log4net 包装器一起使用

javascript - 初始加载和更新之间的 SignalR

c# - 任何人都可以知道该怎么做(错误CS1525 : Unexpected symbol)

c# - 迁移到.Net时如何避免从头开始重写VB6

CSS :after overriding existing styles

asp.net - asp.net 在 iis 中访问该路径被拒绝

c# - Winforms IOC 容器 - 组合根

c# - 使用 Autofixture、Moq 和 XUnit 的类中的部分模拟方法

iis - 网页无法访问文件夹。 (IIS)

asp.net-mvc - 用IoC在Controller中注入(inject)HttpContextBase的目的是什么