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