2012-02-15 5 views
3

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

답변

1

나는 그렇게하지 않을 것이다. 한 가지 예로 Mark Seemann의 "Dependency Injection in .NET"은 Service Locator가 사실상 반 패턴임을 보여줍니다. 대신 Nuget을 사용 NinjectMVC3의 최신 버전을 가지고 있다면, 당신은

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

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

그러나 깨끗한 위해 Application_Start 방법으로 끝낼해야

어쨌든 당신의 Global.asax 파일을 부풀게하지 않으려 고 , 당신이 원한다면이 방법의 끝에이 줄을 추가 할 수 있습니다. 아담과 스티브가 Apress MVC3 서적의 Sportstore 응용 프로그램에서하는 것입니다. 그 책이 출시 된 이후

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

는 Ninject에 사실 내가 나오는 끝나 Apress의 MVC4 책은 간단한 방법을 보여줍니다 보장 할 것, 그것은 훨씬 쉽게 최신 버전을 발표했다. 간단한 방법은 Nugget을 사용하고 NinjectMVC3을 얻는 것입니다. 그러면 응용 프로그램 시작시 파일을 실행할 App_Start 폴더가 생깁니다.

여기 그래서 당신의 코드는 다음과 같아야합니다 귀하의 NinjectDependencyResolverIDependencyResolver에서 상속해야합니다

+0

이 책의 코드를하려고하면 나는 IProductRepository 사용 제공자가 null 반환 상수 값에 IProductRepository에서 바인딩을 활성화하는 erorr "오류를 얻을 활성화 경로를 :. 2) 형 ProductController의 생성자의 매개 변수 productRepository에 의존 IProductRepository 사출 1) ProductController에 대한 요청 제안 : 1) 공급자가 생성 요청을 올바르게 처리하는지 확인하십시오. " – MasterP

+0

이 오류가 발생합니다. IController GetControllerInstance (RequestContext requestContext, type controllerType) { return controllerType == null ? null : (IController) ninjectKernel.Get (controllerType); } – MasterP

+0

문제가 해결되었다고 말씀 하시겠습니까? 그렇지 않다면 더 설명 할 수 있을까요? –

2

일부 바인딩

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

    }   
} 

}로의 예입니다

public class NinjectDependencyResolver : IDependencyResolver