简体   繁体   中英

Ninject and asp.net MVC4

I have a MVC3 application that I would like to port to MVC4. I am using Ninject for dependency injection. Using Nuget, I added "Ninject" to my project and created a controller factory as shown below

public class NinjectControllerFactory : DefaultControllerFactory
{
    private IKernel ninjectKernel;

    public NinjectControllerFactory()
    {
        ninjectKernel = new StandardKernel();
        AddBindings();
    }

    protected override IController GetControllerInstance(RequestContext  requestContext, Type controllerType)
    {
        return controllerType == null ? null : (IController)ninjectKernel.Get(controllerType);
    }

    private void AddBindings()
    {
        //Add ninject bindings here
    }
}

This works fine for MVC3 but things have changed in MVC4. I did some digging and found this link that explains how to get ninject working for MVC4

http://haacked.com/archive/2012/03/11/itrsquos-the-little-things-about-asp-net-mvc-4.aspx

However, I am having trouble getting the code in the above link to compile. Specifically, The code that I am supposed to place in the Start() method of the web.common file gives me unresolved namespace errors

GlobalConfiguration.Configuration.ServiceResolver
  .SetResolver(DependencyResolver.Current.ToServiceResolver());

Both "ServiceResolver" and ".SetResolver" are unresolved. What references do I need to add to enable these? Also, if possible can you point me towards a tutorial showing me how to get ninject working in MVC4 without having to install the nuget package ninject.mvc3? I ask because I would prefer not to have any packages installed in my application that were written for MVC3 specifically to avoid things from breaking down the line if these nuget packages are updated.

edit: I should have added that I am using Visual studio 2012 and .Net 4.5

Phil's article is about using Ninject with WebAPI. Is that what you mean? You don't need to do that for normal MVC injection. Also, you should be using the Ninject.MVC3 NuGet package with MVC4 (yes, I know it says MVC3, but it still works fine because NuGet sets up Assembly Version Redirects that make everything Just Work), this sets everything up and you don't need a controller factory. Just edit the NinjectWebCommon.cs file to add your bindings.

Just simply Add namespace

Using Ninject;

after installing template from Nuget... U just install "Ninject" but not "Ninject for MVC3" from Nuget Template

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM