12

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?

Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
Chris S
  • 64,770
  • 52
  • 221
  • 239

2 Answers2

34

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.

Colin Mackay
  • 18,736
  • 7
  • 61
  • 88
  • I'm not really sure you really defined any reason. You merely explained why statics in web environments can result in unexpected behaviors. – Chris Marisic May 25 '11 at 20:43
  • 11
    Surely the fact that it can "result in unexpected behaviours" is a valid reason for not using them as part of the ASP.NET MVC framework. My answer is, of course and as I indicated, speculative as I don't know the minds of those that created the framework. However, it is still a potential reason. – Colin Mackay May 25 '11 at 21:46
  • 1
    You could also add DI and testability to the reasons they're not static – Chris S Feb 26 '13 at 10:53
  • 1
    The question is asking about static methods, not static controllers – user3163495 Mar 28 '19 at 17:18
1

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.

  • They would be in different classes, and you can have private static methods. The benefit of static is that it would block access to instance fields. Unnecessary access to members is a common way that OOP programs develop bugs... especially when someone wants to shoehorn in a change on a Friday... "I can just add a boolean here, what's the harm?" (Note that this statement doesn't really apply to a Web API controller.) – ScottMichaud Aug 02 '21 at 01:14