In this post I will discuss a possible solution for having Castle Windsor resolving types for both MVC controllers and Web API controllers. Since the former is well known I will focus mostly on the Web API part.
A team building a mobile web application uses the ASP.NET MVC stack combined with another web services framework. With the release of the Beta version of ASP.NET MVC 4 they decided to give Web API a try (side by side with MVC controllers) and see if it fits their needs.
The Controller-derived types are used only for rendering the views (the code is written in JavaScript) while the ApiController-derived types are used for returning data to the client.
The DependencyResolver class provides a method called SetResolver which acts as a registration point for resolving dependencies.
Be careful as there are more than one DependencyResolver types. One defined in System.Web.Mvc namespace and one defined in System.Web.Http namespace. We need the latter here.
Once we define the delegates and set a breakpoint we can see what types the framework requests.
At first an instance of the IHttpControllerFactory type is requested:
Followed by a request for an instance of the ILogger type and so on.
The first thing we want to do is to create a type implementing the IHttpControllerFactory interface.
Note that inside the WindsorHttpControllerFactory class the CreateController method takes a string for the name of the controller. That means we need to use the Windsor's Named method to set a name for each controller registration. (We can also trim the "Controller" part from the name and also pluralize the remaining part.)
Let's also create a NullLogger implementing the ILogger interface.
For all the other instances that the framework requests there are default implementations in the System.Web.* assemblies and we can now create a Windsor Installer to encapsulate the registration logic.
In the Application_Start method we add the installer and set the delegates for the SetResolver method. That way when the framework requests an IHttpControllerFactory instance, Windsor will supply the one we created earlier.
In order to have Windsor resolve regular controllers (side by side) we can create and add another installer as well as an implementation of the IControllerFactory interface.
Finally, a gist with all the source code can be found here.
References: