ASP.NET MVC controllers static methods

2019-01-23 07:51发布

问题:

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 2 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?

回答1:

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.