MVC2 Using Unity IoC - How are controllers resolved?
I have a question concerning how the Unity container I have set up is resolving controller dependencies. I've been searching around for an explanation of this but haven't found anything that is real clear on the subject. And maybe the answer is staring me in the face... Take a look at the following code that I'm sure many MVC guys have seen:
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
IController controller;
try
{
controller = container.Resolve(controllerType) as IController;
}
catch (Exception ex)
{
throw ne开发者_StackOverflow中文版w InvalidOperationException(string.Format("Error resolving controller {0}", controllerType.Name), ex);
}
return controller;
}
So that is my override of GetControllerInstance
in my controller factory that I have set up. Obviously, the controller types are being resolved out of the Unity container but how are they getting registered in the container in the first place? How does the MVC framework know to register types in the container? I realize that the types are being resolved out of that container but I don't like not knowing how it is resolving the controller types.
It is the DefaultControllerFactory which is responsible for this. Here's how it works:
ASP.NET MVC uses reflection to list all types that inherit from Controller
in all assemblies and caches them. If you really want to dig further look at the source code or use reflector and checkout this method on the DefaultControllerFactory
type:
protected internal virtual Type GetControllerType(
RequestContext requestContext, string controllerName)
When a request comes it uses the routing table to determine which is the current controller and tries to find it in the list of cached controller types. If it finds one it calls the GetControllerInstance
method passing the given type so that the DI framework could provide the controller instance given its type.
MVC does not register the types with Unity. The Unity container inspects what you ask for to see if it can instantiated it with what it knows about.
精彩评论