且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET MVC 控制器静态方法

更新时间:2022-11-23 12:53:36

虽然我不知道那些设计 ASP.NET MVC 框架的人的想法,但这里对我来说很重要:

每个请求实例化一个实例控制器,多个请求可以同时发生.如果控制器是静态的,那么控制器上的任何状态都会在所有请求中同时共享.你可能不想那样.更新共享状态会成为锁定争用的雷区,可能会导致死锁,并且如果锁定未正确实施,则很难跟踪错误.

简而言之,使用静态控制器将是一场噩梦.

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?

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.