2011-06-12 82 views
4

我有這樣的接口:Ninject構造函數的參數

public interface IUserProfileService 
{ 
    // stuff 
} 

實現方式:

public class UserProfileService : IUserProfileService 
{ 
    private readonly string m_userName; 

    public UserProfileService(string userName) 
    { 
     m_userName = userName; 
    } 
} 

我需要這個注入這樣的控制器:

public class ProfilesController : BaseController 
{ 
    private readonly IUserProfileService m_profileService; 

    public ProfilesController(IUserProfileService profileService) 
    { 
     m_profileService = profileService; 
    } 
} 

我不知道如何將此接口及其實現註冊到Ninject容器中,以便在Ninject進入時傳入userName參數這項服務的立場。

任何想法,我可以如何實現這一點?

+3

我與邁克所描述的一致。對於更多細節和解釋,我建議閱讀Ruben Bartelink的答案:http://stackoverflow.com/questions/2227548/creating-an-instance-using-ninject-with-additional-parameters-in-the-constructor 。這是你想要實現的一個非常徹底的答案。 – Khepri 2011-06-12 16:33:47

+0

有人能解釋他們爲什麼低估了這個問題嗎? – ryber 2012-11-02 23:55:11

回答

3

一種替代方法是注入一個工廠並使用Create(string userName)創建您的依賴關係。

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

這似乎關閉以創建另一個類,但是當UserProfileService需要在額外的依賴帶來的好處主要是來了。

+0

ProfilesController構造函數是否接受UserProfileServiceFactory和userName? – JDawg 2015-01-23 22:07:28

3

訣竅是不是在該類中注入用戶名。你稱這個類爲服務,所以它可能會與多個用戶透明地工作。我看到了兩個解決方案:

  1. 注入抽象成表示當前用戶的服務:

    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 
        } 
    } 
    
  2. 創建特定於您正在使用該技術的實現,例如:

    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

在選項一上,假設IPrincipal的具體構造函數接受一個userName參數,該選項如何提供幫助? – JDawg 2015-01-23 21:55:39

5

技術ninject答案是使用構造函數的參數,像這樣:

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

當然,你需要弄清楚這裏的「卡爾」的由來。這真的取決於你的應用程序。也許它是一個Web應用程序,它在HttpContex上?我不知道。如果它變得相當複雜,那麼你可能想寫一個IProvider而不是做一個常規的綁定。