MVC,不是“假设"使用 HttpContext.Current 了? [英] MVC, not "supposed" to use HttpContext.Current anymore?

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

问题描述

有人在这里评论说你使用 MVC 时不应使用 HttpContext.Current,而应使用 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 变量,我都需要引用 Controller?为什么我们不应该"在 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?

我知道测试方面,由于许多其他地方所述的原因,它更好,但我正在开发一个管理会话变量和引用 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 也使代码更加脆弱,因为它可能被滥用和误用.例如,您可以在业务层使用它,因为它很方便,但如果您选择使用 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,不是“假设"使用 HttpContext.Current 了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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