Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the generated NinjectMVC3.cs from NuPack not compile? (or what happened to MvcServiceLocator in ASP.NET MVC 3 Beta? )

Using the NuPack addin and installing the NInject MVC 3 package results in the following compile error in the generated NinjectMVC3.cs file.

The name 'MvcServiceLocator' does not exist in the current context

The sample video David Ebbo posted shows it working just fine at 09:43.

Here is the currently generated class:

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

    public static void SetupDependencyInjection() {
        // Create Ninject DI Kernel 
        IKernel kernel = new StandardKernel();

        // Register services with our Ninject DI Container
        RegisterServices(kernel);

        // Tell ASP.NET MVC 3 to use our Ninject DI Container 
        MvcServiceLocator.SetCurrent(new NinjectServiceLocator(kernel));
    }
}
like image 303
Jedidja Avatar asked Oct 06 '10 17:10

Jedidja


2 Answers

Basically, MvcServiceLocator has gone away. Whenever the video was made there was a mismatch in versions, I guess.

There are excellent explanations available here and here.

The two steps that will make Ninject work are as follows. Replace NinjectMVC3 with the following (I also changed the name which isn't necessary):

public class NinjectResolver : IDependencyResolver
{
    private static IKernel kernel;

    public NinjectResolver()
    {
        kernel = new StandardKernel();
        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 add the following line to App_Start() in gloabl.asax.cs

DependencyResolver.SetResolver(new NinjectResolver());
like image 187
Jedidja Avatar answered Sep 30 '22 13:09

Jedidja


I have fixed the package and uploaded it to the feed. It would be great if you had a chance to try it and verify that it works now. I upped the version of Ninject.MVC3 from 0.1 to 0.2 :)

like image 21
David Ebbo Avatar answered Sep 30 '22 12:09

David Ebbo