2011-06-12 5 views
4

나는이 인터페이스를 가지고 이 인터페이스와 그 구현을 Ninject 컨테이너에 등록 할 수있는 방법. 그래서 Ninject가 inits inits in 인 경우 userName 매개 변수가 전달됩니다. 이 서비스의 자세.Ninject에 생성자 인수

어떻게하면이 아이디어를 얻을 수 있습니까?

+3

저는 마이크가 설명한 것과 일반적으로 일치합니다. 좀 더 자세한 내용과 설명에 대해서는 Ruben Bartelink의 대답을 읽어 보시기 바랍니다 : http://stackoverflow.com/questions/2227548/creating-an-instance-using-ninject-with-additional-parameters-in-the-constructor . 이것은 당신이 달성하고자하는 것에 대한 철저한 답입니다. – Khepri

+0

누군가이 질문에 왜 싫어하는 지 설명 할 수 있습니까? – ryber

답변

3

하나의 대안은 공장을 삽입하고 Create(string userName)을 사용하여 종속성을 만드는 것입니다.

public class UserProfileServiceFactory 
{ 
    public IUserProfileService Create(string userName) 
    { 
     return new UserProfileService(userName); 
    } 
} 

또 다른 클래스를 생성해야 할 떨어져 보일 수도 있지만 UserProfileService 추가 의존성에 걸리는 경우 혜택은 주로 온다.

+0

그런 다음 ProfilesController 생성자가 UserProfileServiceFactory와 userName을 사용합니까? – JDawg

3

트릭은 이 아니며 사용자 이름을 해당 클래스에 삽입합니다. 이 클래스를 서비스이라고 부르므로 여러 사용자가 transparantly 작동합니다.

public class UserProfileService : IUserProfileService 
{ 
    private readonly IPrincipal currentUser; 

    public UserProfileService(IPrincipal currentUser) 
    { 
     this.currentUser = currentUser; 
    } 

    void IUserProfileService.SomeOperation() 
    { 
     var user = this.currentUser; 

     // Do some nice stuff with user 
    } 
} 
  • 는 예를 들어, 작업중인 기술에 특정한 구현을 만들기 :

    1. 현재 사용자를 나타내는 서비스로 추상화를 주입 : 나는 두 가지 솔루션을 참조

      public class AspNetUserProfileService : IUserProfileService 
      { 
          public AspNetUserProfileService() 
          { 
          } 
      
          void IUserProfileService.SomeOperation() 
          { 
           var user = this.CurrentUser; 
      
           // Do some nice stuff with user 
          } 
      
          private IPrincipal CurrentUser 
          { 
           get { return HttpContext.Current.User; } 
          } 
      } 
      

    당신은 옵션 하나를 이동 할 수 있습니다.

  • +0

    옵션 1에서 IPrincipal의 concrete 생성자가 userName 인수를 취한다고 가정 할 때이 옵션이 어떻게 도움이됩니까? – JDawg

    5

    기술적 Ninject에 대답과 같이 생성자 인자를 사용하는 것입니다 : 물론

    Bind<IUserProfileService>().To<UserProfileService>().WithConstructorArgument("userName", "karl"); 
    

    는 "칼"은 어디에서 오는지 알아낼 필요가있다. 앱에 따라 다릅니다. 어쩌면 자사의 웹 애플 리케이션과 그것은 HttpContex에있어? 나는 모른다. 다소 복잡해지면 정규 바인딩을 사용하는 대신 IProvider를 작성하는 것이 좋습니다.