C# 注入到ToMethod绑定中

C# 注入到ToMethod绑定中,c#,dependency-injection,ninject,C#,Dependency Injection,Ninject,我不太确定该怎么问这个问题,所以我将发布我的代码示例,并简要说明我正在尝试做什么。我有以下绑定设置: kernel.Bind<IAuthenticationService>().To<FormsAuthenticationService>(); kernel.Bind<IAuthenticationService>().To<TokenAuthenticationService>().When(r => HasAncestorOfType&l

我不太确定该怎么问这个问题,所以我将发布我的代码示例,并简要说明我正在尝试做什么。我有以下绑定设置:

kernel.Bind<IAuthenticationService>().To<FormsAuthenticationService>();
kernel.Bind<IAuthenticationService>().To<TokenAuthenticationService>().When(r => HasAncestorOfType<MyWebApiController>(r));
这不管用
iaauthenticationservice
总是绑定到
FormsAuthenticationService

解决方案不起作用的原因很简单,就是
请求。Target
不能作为控制器,因为您是通过“您自己”
内核.Get()请求(请求)实例的

我会让
公司
像这样:

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>();
kernel.Bind().To();
然后,
request.Target
将成为控制器(位于请求层次结构的根),您将获得正确的服务实现。

解决方案不起作用的原因很简单,
request.Target
不能成为控制器,因为您是通过“您自己”请求(请求)实例的-
kernel.Get()

我会让
公司
像这样:

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>();
kernel.Bind().To();
然后,
request.Target
将成为控制器(位于请求层次结构的根),您将获得正确的服务实现