加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 使用IoC在Controller中注入HttpContextBase的目

发布时间:2020-12-16 03:29:40 所属栏目:asp.Net 来源:网络整理
导读:我已经看到许多使用IoC容器的代码示例,注册如下: // Autofacbuilder.Register(c = new HttpContextWrapper(HttpContext.Current)) .AsHttpContextBase() .InstancePerRequest();// Again Autofac builder.RegisterModule(new AutofacWebTypesModule()); (参
我已经看到许多使用IoC容器的代码示例,注册如下:

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

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

(参见src for AutofacWebTypesModule HERE)

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

与使用构造函数注入的控制器一起:

public class HomeController : Controller
{
    private readonly HttpContextBase _httpContext;

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

问题1:

你能解释一下包装HttpContextBase,HttpRequestBase等的原因吗?

问题2:

注入的HttpContextBase与HttpContext(Controller的属性)与System.Web.HttpContext.Current之间的区别是什么?

更新

问题3:

在代码中使用哪个HttpContext,Injected One或者它也可以通过HttpContext和System.Web.HttpContext.Current调用它?如果两种方式都有问题吗?

解决方法

答案1

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

通过让IOC容器处理它,您可以注册在测试时注入组件的不同/确定性实例.在普通代码中,您将注入作为默认实现的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

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

答案3

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读