2013-05-10 54 views
1

我不太清楚如何問這個,所以我只是發佈我的代碼示例,並給出我想要做的簡要描述。我有以下的綁定設置:注入ToMethod綁定

kernel.Bind<IAuthenticationService>().To<FormsAuthenticationService>(); 
kernel.Bind<IAuthenticationService>().To<TokenAuthenticationService>().When(r => HasAncestorOfType<MyWebApiController>(r)); 

下面是HasAncestorOfType代碼(雖然我認爲這是無關緊要這裏):

private static bool HasAncestorOfType<T>(IRequest request) 
{ 
    if (request.Target == null) 
     return false; 

    if (request.Target.Member.ReflectedType == typeof(T)) 
     return true; 

    return HasAncestorOfType<T>(request.ParentRequest); 
} 

這些綁定的預期都工作(IAuthenticationService勢必FormsAuthenticationService除非被注入進入MyWebApiController,在這種情況下,它必然是TokenAuthenticationService)。但是,我想,這樣ICurrentCompany獲取綁定,從IAuthentcationService創建的對象來創建一個工廠這樣的結合:

kernel.Bind<ICurrentCompany>().ToMethod(x => new Company { CompanyId = x.Kernel.Get<IAuthenticationService>().User.CompanyId}); 

這是行不通的。 IAuthenticationService始終與FormsAuthenticationService綁定。

回答

1

之所以您的解決方案不工作很簡單,就是request.Target無法控制,因爲你所問的「你的自我」(請求)的實例 - kernel.Get<>()

我會讓Company這樣的:

public class Company : ICurrentCompany{ 

    public int CompanyId { get; private set;} 

    public class Company(IAuthenticationService authenticationService){ 
      this.CompanyId = authenticationService.User.CompanyId; 
    } 
} 

,然後簡單地結合:

kernel.Bind<ICurrentCompany>().To<Company>(); 

request.Target將作爲控制器(位於請求層次結構的根部),您將得到正確的服務實現。