MVC,不是"应该"使用HttpContext.Current了吗? [英] MVC, not "supposed" to use HttpContext.Current anymore?

查看:609
本文介绍了MVC,不是"应该"使用HttpContext.Current了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人在后<一个href=\"http://stackoverflow.com/questions/2497575/asp-net-mvc-unit-test-controller-with-httpcontext\">here,评论说,你不应该使用HttpContext.Current使用MVC的时候,相反,你应该使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.controllerbase.controllercontext.aspx\">ControllerBase.ControllerContext.在某些方面,这是有道理的,但在其他方面没有。

Someone in a post here, commented that you should not use HttpContext.Current when using MVC, rather, you should be using ControllerBase.ControllerContext. In some respects, this makes sense, but in other respects it doesn't.

例如,ControllerContext是一个实例变量,所以无论我要引用,说,我的Session变量,我需要到控制器的参考?为什么我们不应该,在MVC中使用HttpContext.Current,当你仍然可以?是否有一个适当MVC的方式来获得我的Session对象,而不必有到控制器的参考?

For example, ControllerContext is an instance variable, so everywhere I want to reference, say, my Session variables, I need to have a reference to the Controller? Why are we "not supposed" to be using HttpContext.Current in MVC, when you still can? Is there an "appropriate" MVC "way" to get at my Session object without having to have a reference to the Controller?

我知道测试的角度来看,这是很多其他地方所阐述的理由更好,但我的工作是管理Session变量和引用HttpContext.Current一个项目,我想知道是否有更好的办法让我的Session对象手上没有通过引用到控制器。

I know test-wise, it is better for reasons stated in many other places, but I am working on a project that manages Session variables and references HttpContext.Current and I want to know if there is a better way to get my hands on the Session object without passing a reference to the controller.

推荐答案

这是因为主要的单元测试是,如果你使用非常困难 HttpContext.Current 嘲讽,因为这个值是不是可以使用正常的模拟框架。

This is mainly since unit testing would be very difficult if you use HttpContext.Current since mocking this value is not possible using normal mock frameworks.

HttpContext.Current 也使得更脆code,因为它可以被滥用和误用。例如,你可以使用它在业务层,因为它很方便,但如果你选择使用替代presentation比ASP.NET另一层这将打破。

HttpContext.Current also makes for more brittle code since it can be abused and misused. For example, you can use it in business layer since it is convenient but it will break if you choose to use an alternative presentation layer other than ASP.NET.

一般静态方法时,因为它们不能被时下皱起了眉头依赖注入

Generally static methods are nowadays frowned upon since they cannot be dependency-injected.

这篇关于MVC,不是&QUOT;应该&QUOT;使用HttpContext.Current了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆