65.9K
CodeProject is changing. Read more.
Home

Using the ControllerActivator in MVC 3

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.67/5 (2 votes)

Oct 18, 2010

CPOL

1 min read

viewsIcon

18415

How you can use the ControllerActivator in order to activate controllers using your own behavior

In the previous post, I showed how to use the DependencyResolver in order to bring Dependency Injection behavior to a MVC 3 application. In this post, I’ll show you how you can use the ControllerActivator in order to activate controllers using your own behavior.

The IControllerActivator

In MVC 3 beta, a new interface was introduced – the IControllerActivator. This interface is an injection point in order to create our own behavior in order to activate controllers. That interface is discoverable using the dependency resolver. If you don’t implement the interface and register it in the dependency resolver, a default behavior which is to use the Activator.CreateInstance will activate controllers.

The interface includes only one method which is the Create method. This method has the same signature like the DefaultControllerFactory’s GetControllerInstance method.

Here is a simple way to implement the IControllerActivator using the previous post’s DependencyResolver:

public class UnityControllerActivator : IControllerActivator
{
  #region IControllerActivator Members
 
  public IController Create(RequestContext requestContext, Type controllerType)
  {
    return DependencyResolver.Current.GetService(controllerType) as IController;      
  }
 
  #endregion
}

As you can see, I use the current DependencyResolver to get the Unity behavior. Of course, you can use other behaviors to implement the controller activation. Here is how the InitContainer method from the previous post will look like now:

private static IUnityContainer InitContainer()    
{
  var container = new UnityContainer();        
 
  // Register the relevant types for the         
  // container here through classes or configuration 

  container.RegisterType<IControllerActivator, UnityControllerActivator>();                
  container.RegisterType<IMessageService, MessageService>();

  return container;
}

I just added the registration of the IControllerActivator to the container. Now if you will debug the application and set a breakpoint in the Create method, you will see that all controller activations will pass through the IControllerActivator. When running the application, you will get the same result as in the previous post:

HomeController Result

Summary

In this post, I showed how to hook up your own controller activation behavior in MVC 3. This can be achieved by using the new IControllerActivator interface. The example I showed is using the Unity IoC and could be implemented in other ways as well.