ninject依赖项解析器和服务定位器实现

时间:2012-02-15 00:23:02

标签: asp.net-mvc-3 ninject

我正在学习ASP.NE4 MVC3。我已经创建了一个NinjectDependencyResolver类,但我想知道如何实现ServiceLocator类。目前我收到此错误“类型SportsStore.WebUI.Infrastructure.NinjectDependencyResolver似乎没有实现Microsoft.Practices.ServiceLocation.IServiceLocator。 参数名称: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>();
            }
        }

3 个答案:

答案 0 :(得分:2)

您的NinjectDependencyResolver必须继承自IDependencyResolver,因此您的代码应如下所示:

public class NinjectDependencyResolver : IDependencyResolver

答案 1 :(得分:1)

答案 2 :(得分:1)

我不会那样做。一方面,Mark Seemann的书“.NET中的依赖注入”清楚地表明Service Locator实际上是一种反模式。

无论如何,尽量不要膨胀你的global.asax文件

如果您改为使用Nuget并获得最新版本的NinjectMVC3,那么最终应该使用干净的Application_Start方法

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

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

但是,如果你愿意,你可以将这一行添加到该方法的末尾,因为我相信这是Adam和Steve在Apress MVC3书中的Sportstore应用程序中所做的。

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

自那本书发布以来,Ninject发布了更新版本,使其变得更加容易,事实上我保证最终出来的Apress MVC4书籍将显示更简单的方式。简单的方法是使用nuget并获取NinjectMVC3,然后它将有一个App_Start文件夹,它将在应用程序启动时运行其中的文件。

以下是一些带有一些绑定的例子

 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>();

    }        
}

}