Ninject in ASP.NET MVC4

前端 未结 8 1946
终归单人心
终归单人心 2021-02-07 03:19

So after much screwing around I finally got Ninject wired in and compiling in my MVC4 application. The problem I was running into is the IDependencyScope interface no longer ex

8条回答
  •  闹比i
    闹比i (楼主)
    2021-02-07 04:06

    Check out the Pro ASP.NET MVC 3 book. I just ported this code over from MVC3 to MVC4 last night and works correctly. Page 322 to be exact.

    What I don't see is where you are mapping your Interface to your concrete items.

    Bind().To();
    

    Add another constructor and add the method that calls your mapping;

    public NinjectDependencyResolver() {
        _kernal = new StandardKernel();
        RegisterServices(_kernel);
    }
    
    public static void RegisterServices(IKernel kernel) {
        kernel.Bind().To();
    }
    

    Here's what a resolver could/should look like;

       public class NinjectDependencyResolver : IDependencyResolver {
        private IKernal _kernel;
    
        public NinjectDependencyResolver(){
            _kernal = StandardKernal();
            AddBindings();
        }
    
        public NinjectDependencyResolver(IKernel kernel)
        {
            _kernel = kernel;
        }
    
        public object GetService(Type serviceType)
         {
             return _kernel.TryGet(serviceType);
         }
    
         public IEnumerable GetServices(Type serviceType)
         {
            return _kernal.GetAll(serviceType);
         }
    
        public IBindingToSyntax Bind() {
          return _kernal.Bind();
        }
    
         public static void RegisterServices(IKernel kernel){
          //Add your bindings here. 
          //This is static as you can use it for WebApi by passing it the IKernel
         }
    }
    
    
    

    Global.Asx -

    Application_Start()

    method

    DependencyResolver.SetResolver(new NinjectDependencyResolver());
    

    That's it.


    UPDATED 11/14/2012

    On a side note, if you're working with MVC WebAPI, you will want to use WebApiContrib.IoC.Ninject from nuget. Also, check out the "Contact Manager" in their samples asp.net.com. This helped to cleanup the implementation of Ninject

    提交回复
    热议问题