ASP.NET MVC 控制器静态方法
最近工作中出现了关于为什么 ASP.NET MVC 不使用静态方法作为其控制器方法的讨论。虽然我反对使用静态方法,但对于非静态操作方法,我认为唯一的两个参数是继承和模拟能力(继承为您提供了这种能力)。
相对于静态,Microsoft 对非静态操作/方法的设计选择是什么?
A discussion came up at work recently about why ASP.NET MVC doesn't use static methods for its controller methods. Whilst I was on the side of the fence against using static methods, the only two arguments I could think for non-static action methods were inheritence and the ability to mock (which inheritence gives you).
What was Microsoft's design choice for non-static actions/methods over static?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然我不知道设计 ASP.NET MVC 框架的人的想法,但这里对我来说是一个大问题:
每个请求实例化一次实例控制器,多个请求可以同时发生。如果控制器是静态的,则控制器上的任何状态都会同时在所有请求之间共享。你可能不想要这样。更新共享状态会成为锁定争用的雷区,可能会出现死锁,并且如果锁定未正确实现,则很难跟踪错误。
简而言之,使用静态控制器将是一场噩梦。
While I don't know minds of those that designed the ASP.NET MVC Framework here is the big one for me:
An instance controller is instantiated once per request, multiple requests can be happening simultaneously. If a controller is static then any state on the controller is shared across all requests simultaneously. You probably don't want that. Updating that shared state becomes a minefield of locking contention, possible deadlocks and very hard to track bugs if locking isn't implemented properly.
In short, a static controller would be a nightmare to work with.
例如,您有控制器“Home”和操作“FillData”,
另一个控制器“Student”和操作“FillData”。
想象一下,如果您将“FillData”操作设置为静态方法,并且可以在任何其他控制器中轻松调用,将会发生什么。
这将是一个大问题。
You have for example controller "Home" and action "FillData",
and another controller "Student" and action "FillData".
Imagine what will happen if you make action "FillData" a static method, and could be called in any other controller easily.
It would be a big ISSUE.