Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC controllers static methods

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?

like image 897
Chris S Avatar asked May 25 '11 15:05

Chris S


People also ask

CAN controller have static methods?

Yes you can but you need to make a static class and access the static class inside the controller. You can just put it in a class like below. Then you can call it from any of your controllers, no matter what their base class is.

Can action method be static in MVC?

- Action method cannot be a static method. ActionResult is a base class of all the result type which returns from Action method.

What is ActionResult () in MVC?

What is an ActionResult? An ActionResult is a return type of a controller method, also called an action method, and serves as the base class for *Result classes. Action methods return models to views, file streams, redirect to other controllers, or whatever is necessary for the task at hand.

Why TempData is used in MVC?

What is TempData and How to Use in MVC? TempData is used to transfer data from the view to the controller, the controller to the view, or from an action method to another action method of the same or a different controller. TempData temporarily saves data and deletes it automatically after a value is recovered.


2 Answers

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.

like image 155
Colin Mackay Avatar answered Sep 20 '22 10:09

Colin Mackay


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.

like image 35
Mohammed Khalil Avatar answered Sep 22 '22 10:09

Mohammed Khalil