gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:54:43 25 4
gpt4 key购买 nike

我见过很多使用 IoC 容器进行注册的代码示例,例如:

// Autofac
builder.Register(c => new HttpContextWrapper(HttpContext.Current))
.As<HttpContextBase>()
.InstancePerRequest();

// Again Autofac
builder.RegisterModule(new AutofacWebTypesModule());

(请参阅 AutofacWebTypesModule 的 src HERE )

// Castle Windsor
container.Register(Component.For<HttpContextBase()
.LifeStyle.PerWebRequest
.UsingFactoryMethod(() => new HttpContextWrapper(HttpContext.Current)));

与使用构造函数注入(inject)的 Controller 一起:

public class HomeController : Controller
{
private readonly HttpContextBase _httpContext;

public HomeController(HttpContextBase httpContext)
{
_httpContext = httpContext;
}
//....
}

问题 1:

您能解释一下包装 HttpContextBase、HttpRequestBase 等的原因吗?

问题 2:

注入(inject)的HttpContextBaseHttpContext( Controller 的属性)与System.Web.HttpContext.Current之间有什么区别

更新

问题 3:

在代码中使用哪个HttpContext,注入(inject)的或者通过HttpContextSystem.Web.HttpContext.Current调用它也很好强>?双向调用有什么问题吗?

最佳答案

答案1

HttpContext 在测试方面是一个臭名昭著的痛苦,因为它只存在于请求的上下文中。 Since .net 3.5 HttpContextBase is an abstraction of HttpContext并适合通过 IOC 框架注入(inject)

通过让 IOC 容器处理它,您可以注册一个不同的/确定性的实例,并在测试时注入(inject)到您的组件中。在普通代码中,您将注入(inject)默认实现的 HttpContextWrapper

从链接页面:

The HttpContextBase class is an abstract class that contains the same members as the HttpContext class. The HttpContextBase class enables you to create derived classes that are like the HttpContext class, but that you can customize and that work outside the ASP.NET pipeline. When you perform unit testing, you typically use a derived class to implement members with customized behavior that fulfills the scenario you are testing.

答案2

注入(inject)的HttpContextBase将返回测试成功所需的数据:特定的查询字符串、特定的查询等。通常注入(inject)的实现仅包含测试所需的方法。测试,忽略所有其他属性,例如上下文 .User.Identity.Name 属性以测试身份验证。

答案3

在代码中,您必须始终使用注入(inject)的HttpContextBase,因为您不想依赖于可能在测试时失败的具体实现。如果同时调用这两种方式,您可能会遇到问题,尤其是在测试中,因为 HttpContext.Current 将返回 null。

关于asp.net-mvc - 用IoC在Controller中注入(inject)HttpContextBase的目的是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25936179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com