Thursday, October 7, 2010

Upgrade ASP.NET MVC 3 Preview to MVC Beta

I previously blogged about upgrading the TekPub ASP.NET 2 Starter Site from MVC2 to MVC3 Preview:
http://blog.cdeutsch.com/2010/08/upgrade-mvc2-to-mvc3.html

Today I upgrade that project to MVC3 Beta.

It was pretty easy. Biggest change was with Dependency Injection. IMvcServiceLocator no longer exits and has been replaced with IDependencyResolver.

My NinjectServiceLocator file has been replaced with NinjectResolver (thanks Jedidja from StackOverflow!) and looks like this:

namespace Mvc3Ninject.Utility
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;
    using Ninject;

    [System.Diagnostics.DebuggerStepThrough]
    public class NinjectResolver : IDependencyResolver
    {
        private static IKernel kernel;

        public NinjectResolver()
        {
            kernel = new StandardKernel();
            RegisterServices(kernel);
        }

        public NinjectResolver(IKernel myKernel)
        {
            kernel = myKernel;
            RegisterServices(kernel);
        }

        public static void RegisterServices(IKernel kernel)
        {
            //kernel.Bind<IThingRepository>().To<SqlThingRepository>();
        }

        public object GetService(Type serviceType)
        {
            return kernel.TryGet(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return kernel.GetAll(serviceType);
        }
    }

}

And then in the Global.asax.cs file I changed this line....

//// Tell ASP.NET MVC 3 to use our Ninject DI Container 
MvcServiceLocator.SetCurrent(new NinjectServiceLocator(_container));

...to...

//// Tell ASP.NET MVC 3 to use our Ninject DI Container 
DependencyResolver.SetResolver(new NinjectResolver(_container));

And that's that! Have fun coding!

Here's a complete working sample project based on my Code-First Entity Framework upgrade of the TekPub Starter Site.