Search code examples
asp.net-mvc-3ninject

ninject dependency resolver and service locator implementation


I am learning ASP.NE4 MVC3. I have created a NinjectDependencyResolver class, but I want to know how I would go about implementing the ServiceLocator class. Currently I get this error "The type SportsStore.WebUI.Infrastructure.NinjectDependencyResolver does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator. Parameter name: commonServiceLocator".

Global.asax
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            RegisterDependencyResolver();

            //ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
        }

        private void RegisterDependencyResolver()
        {
            var kernel = new StandardKernel();

            DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));

        }

        NinjectDepencyResolver cs
            public class NinjectDependencyResolver 
    {
        private readonly IKernel _kernel;

        public NinjectDependencyResolver(IKernel kernel)
        {
            _kernel = kernel;
        }

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

        public IEnumerable<object> GetServices(Type serviceType)
        {
            try
            {
                return _kernel.GetAll(serviceType);
            }
            catch (Exception)
            {
                return new List<object>();
            }
        }

Solution

  • I would not do it like that. For one thing, Mark Seemann's book "Dependency Injection in .NET" clearly shows that Service Locator is actually an anti-pattern.

    At any rate try not to bloat your global.asax file

    If you instead used Nuget and got the latest version of NinjectMVC3 , you should end up with a clean Application_Start method

       protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
    
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }
    

    However, if you want to you can add in this line into the end of that method as I believe this is what Adam and Steve do in the Sportstore application in the Apress MVC3 book.

    ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
    

    Since that book was released, Ninject released newer versions that make it much easier, in fact I would guarantee that the Apress MVC4 book that ends up coming out will show the simpler way. The simple way is use nuget and get NinjectMVC3 , then it will have an App_Start folder which will run the files in them at start of the application.

    Here is an example of it with some bindings

     using Products.Data.Abstract;
     using Products.Data.Concrete;
     using Products.Data.Infrastructure;
    
     [assembly:  WebActivator.PreApplicationStartMethod(typeof(ProductsWeb.App_Start.NinjectMVC3), "Start")]
     [assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(ProductsWeb.App_Start.NinjectMVC3), "Stop")]
    
     namespace ProductsWeb.App_Start
     {
      using System.Reflection;
      using Microsoft.Web.Infrastructure.DynamicModuleHelper;
      using Ninject;
      using Ninject.Web.Mvc;
    
    public static class NinjectMVC3 
    {
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();
    
        /// <summary>
        /// Starts the application
        /// </summary>
        public static void Start() 
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule));
            DynamicModuleUtility.RegisterModule(typeof(HttpApplicationInitializationModule));
            bootstrapper.Initialize(CreateKernel);
        }
    
        /// <summary>
        /// Stops the application.
        /// </summary>
        public static void Stop()
        {
            bootstrapper.ShutDown();
        }
    
        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            RegisterServices(kernel);
            return kernel;
        }
    
        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
    
            kernel.Bind<IProductsRepository>().To<FakeProductsRepository>();
            kernel.Bind<MovieRepository>().To<MovieRepository>();
    
        }        
    }
    

    }