I find it ridiculous that MVC doesn't recognize a controller unless it has 'Controller' appended to the class name. This answer mentions the ControllerDescriptor
and ControllerTypeCache
as the two places in MVC where this convention is set up.
My question is why? It's clearly not a convention over configuration thing, as IsControllerType
in ControllerTypeCache
checks that the class:
IController
"Controller"
Does anybody know the reason for this? After all controllers are likely to be in an actual MVC project, in a folder named 'Controllers', and a simple double click on the file will show us that the class inherits Controller
.
Just seems silly to me - but I was wondering if there is an actual reason they have done this.
EDIT
Just seen this blog post by Phil Haack from yesterday where he discusses the decision this convention - he is of the same mind of me - Probably a bit pointless!
You can always provide a custom controller factory that will resolve these classes differently. And I do agree that controllers need no Controller type name appending because after all they're just like any other class. Their OOP ancestor type defines them as controllers anyway (IController
, Controller
...)
Although it may have something to do with Visual Studio. Similar to Attribute classes. Maybe Visual Studio wouldn't provide additional context menu items to classes that don't end with Controller. When being in controller action you can easily navigate (or create) to the matching view.
So say the experts and I do agree. There are other conventions like these in .net framework as well but people don't complain about them.
Think of collections, dictionaries, attributes, lists and other types that also use similar suffixes without particular reason. They'd work either way, but they're much easier recognisable by their users - developers - who instinctively know how they should work and when to use them.
Imagine having a ProductController
that likely handles Product
application model entity instances. By not having the controller naming convention, we'd have two types with the same name hence would always have to provide namespaces to distinguish between the two. But because we do have this convention this is not necessary and no type clashes occur.
public class ProductController : Controller
{
public ActionResult Index()
{
// we'd have to distinguish this Product type here
IEnumerable<Product> result = GetProducts();
return View(result);
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With