I startted studing the internals from asp.net mvc (6/vnext) and I have a lot of questions but I would like to keep one here. I am using Visual Studio 2015 preview and I saw a new feature in asp.net mvc 6 (or vNext) that controller are not required to inherith from Controller base class. I saw in the asp.net mvc 4/5 the Controller class (or its abstractions) has the properties for resources like TempData, ViewData, ViewBag and method like View(), Json(), File() etc.
Now, in the new version, we are not required to inherit from the Controller base class. So, my question is, how does asp.net mvc knows what resources to add when a controller does not inherit from Controller class? I saw we can add a property and it will be resolved at runtime but how is it done in the asp.net core? Is there a IoC working inside the asp.net core to resolve it?
MVC 6 locates controllers based on a type being public and ending with the suffix Controller. The reality is a bit more complicated than that, and it's also customizable to support other conventions, but that's the essence of it.
Beyond that, MVC 6 has a system to "hydrate" a controller (and views, and other specific types) with required data. This is mostly done with the [Activate] attribute that tells MVC to call into the dependency injection system to populate dependencies on an instance of a class. You can even see in the built-in Controller base class how this is done:
https://github.com/aspnet/Mvc/blob/2353bd911ac137e7858de5bef88af8f7eccaa49f/src/Microsoft.AspNet.Mvc.Core/Controller.cs#L92L99
namespace Microsoft.AspNet.Mvc
{
public class Controller : ...
{
...
[Activate]
public ActionContext ActionContext { get; set; }
[Activate]
public IUrlHelper Url { get; set; }
[Activate]
public IActionBindingContextProvider BindingContextProvider { get; set; }
...
}
}
This is triggered by DefaultControllerFactory here:
https://github.com/aspnet/Mvc/blob/2eef4dd3cf2964136dea9a144b1ee8c21df25c23/src/Microsoft.AspNet.Mvc.Core/DefaultControllerFactory.cs#L41
_controllerActivator.Activate(controller, actionContext);
And that uses an IControllerActivator, and in particular, the DefaultControllerActivator that scans for the [Activate] attribute and assigns values to the properties:
https://github.com/aspnet/Mvc/blob/c16214a53db7f16b06fd9b5a59fa1541e8ecd87a/src/Microsoft.AspNet.Mvc.Core/DefaultControllerActivator.cs
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