Inject (IoC) my MVC3 Application in less than 5 minutes…!

Quickest way to get your MVC3 application up and running with IoC (Inverse of Control) pattern. So let’s start off by first choosing an IoC framework, for this example we will use Ninject, however your more than welcome to choose other IoC frameworks such as Unity, Mef, AutoFac, etc.. I personally prefer Mef, however in this example we will use Ninject so that we can demonstrate how to implement the ServiceLcoator interface to wrap your chose of Ninect container which is accessed by Ninject Kernel, this can come in handy later if you ever decide to switch out your choice of IoC framework.

So let’s start with a fresh new MVC3 application, the first thing on our TODO list is to add Ninject, we are in luck here since we can easily add this with NuGet.

  1. Right click references in your MVC3 project and choose Manage NuGet Packages
  2. Search for “Ninject” in the Search textbox
  3. Your application should be wired up with the Ninject reference added to your project
  4. Add a class named “MyDependencyResolver.cs” anywhere in your MVC3 project, and have it impelment the IDependencyResolver interface. This will allow you to plug pretty much anything into the MVC runtime. The System.Web.Mvc.IDependencyResolver will have two methods that you will need to implement GetService and GetServices.
    
        public class MyDependencyResolver : IDependencyResolver
        {
            public object GetService(Type serviceType)
            {
                throw new NotImplementedException();
            }
    
            public IEnumerable<object> GetServices(Type serviceType)
            {
                throw new NotImplementedException();
            }
        }
    
    
  5. Now let’s wire up our Ninject Kernel (container) in this class MyDependencyResolver.cs
    
        public class MyDependencyResolver : IDependencyResolver
        {
            private readonly IKernel _kernel;
    
            public MyDependencyResolver(IKernel kernel)
            {
                _kernel = kernel;
            }
    
            public object GetService(Type serviceType)
            {
                return _kernel.TryGet(serviceType, new IParameter[0]);
            }
    
            public IEnumerable<object> GetServices(Type serviceType)
            {
                return _kernel.GetAll(serviceType, new IParameter[0]);
            }
        }
    
    

    We create a constructor that accepts IKernel as a parameter, this is where and how the Ninject Kernel will be injected into this class.

  6. Now what we need to do is register MyDependencyResolver with the MVC runtime so that it knows to use it. So let’s head over to Application_Start() in our Global.asax class to wire this up. Here we add a helper method “RegisterMyDependencyResolver” which we will instantiate a new instance of StandardKernel and register it with the MVC runtime using DependencyResolver.SetResolver method which accepts a parameter of IDependencyResolver which our MyDependencyResolver class implemeneted.
    
            protected void Application_Start()
            {
                RegisterMyDependencyResolver();            
                AreaRegistration.RegisterAllAreas();
                RegisterGlobalFilters(GlobalFilters.Filters);
                RegisterRoutes(RouteTable.Routes);
            }
    
            private void RegisterMyDependencyResolver()
            {
                var standardKernel = new StandardKernel();
                DependencyResolver.SetResolver(new MyDependencyResolver(standardKernel));
            }
    
    
  7. Now if we setup a breakpoint on our GetService method we will see that the MVC runtime will first request an instance of System.Web.Mvc.IControllerFactory, now since we haven’t registered or bound an actual class which implements the IControllerFactory interface, our GetService method will just return null, and the MVC runtime will just default to the default ControllerFactory. Now if we had a custom ControllerFactory and had it registered, this would have returned our own instance.

    As you break on on the GetService method, you will notice that the MVC runtime will also request an instance of IControllerActivator, HomeController, IViewPageActivator, Home_Index_cshtml.

  8. Now let’s demonstrate a simple HelloWold injection example. First we want to program against an interface, IHelloWorld with the a method Hello(string message).

    
        public interface IHelloWorldService
        {
            string Hello(string message);
        }
    
    
    

    Now let’s implement this interface, create a HelloWorldService.cs class and implement this interface.

    
        public class HelloWorldService : IHelloWorldService
        {
            public string Hello(string message)
            {
                return message;
            }
        }
    
    
  9. Now we have to register our concrete implementation HelloWorldService to our IHelloWorldService with our container (Kernel), will do this in our Global.asax where we originally fired up our Kernel.
    
            private void RegisterMyDependencyResolver()
            {
                var standardKernel = new StandardKernel();
                standardKernel.Bind<IHelloWorldService>().To<HelloWorldService>();
                DependencyResolver.SetResolver(new MyDependencyResolver(standardKernel));
            }
    
    
  10. Now if we setup a breakpoint in the constructor of our HomeController we will see that the IHomeController parameter will be hydrated by our GetService method of our MyDependencyResolver.GetService method which we registerd as our DependencyResolver with the MVC runtime, this is DependencyInjection.

Download sample: https://skydrive.live.com/redir.aspx?cid=949a1c97c2a17906&resid=949A1C97C2A17906!370&parid=949A1C97C2A17906!361

Stay tuned for Part 2, where we will wire up the ServiceLocator to wrap how we retrieve registered instances so in the event where we wanted to switch out our IoC framework (e.g. Unity, Mef, AutoFac, StructureMap) we would have very little refactoring and code change.

About these ads

One thought on “Inject (IoC) my MVC3 Application in less than 5 minutes…!

Please Leave a Reply or Tweet me @LeLong37...!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s