The recent release of the ASP.NET MVC Framework made a change to the IControllerFactory interface at the request of users of dependency injection containers. Instead of passing the controller factory the type of controller desired, it now gets the string from the route, and the factory can now resolve that type however it wishes.
This fits with most other DI containers, since they have to have everything pre-configured anyway. However, Unity is a little different, in that you don't have to register concrete types ahead of time. This change requires Unity users to register types ahead of time like everyone else, or do reflection to find controller types at runtime. Kind of annoying.
However, there's another answer. Recent (ahem) discussions on the net has shown an obsession with interfaces, to the point that even when there's a useful base class that will solve the problem, many will go straight to the interface and duplicate a lot of work.
In this case, there's a simple way to hook Unity up to ASP.NET MVC preview 2. Rather than implement IControllerFactory, inherit from DefaultControllerFactory instead. There's a method in there, GetControllerInstance, which is called after the name has already been resolved to a type. In other words, the DefaultControllerFactory already does the reflection for you.
Here's the code:
public class UnityControllerFactory : DefaultControllerFactory
{
IUnityContainer container;
public UnityControllerFactory(IUnityContainer container)
{
this.container = container;
}
protected override IController GetControllerInstance(Type controllerType)
{
if (controllerType == null)
{
throw new ArgumentNullException("controllerType");
}
if (!typeof(IController).IsAssignableFrom(controllerType))
{
throw new ArgumentException("Type requested is not a controller", "controllerType");
}
return container.Resolve(controllerType) as IController;
}
To hook this up, in global.asax.cs, do something like this:
IUnityContainer container = new UnityContainer();
// Configure container here
IControllerFactory controllerFactory = new UnityControllerFactory(container);
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
Simple and easy! Hope this helps!
Currently rated 3.2 by 6 people
- Currently 3.166667/5 Stars.
- 1
- 2
- 3
- 4
- 5