Ninject基于控制器注入依赖性

时间:2014-12-03 10:27:09

标签: c# asp.net-web-api ninject ninject.web

我在网络api中使用Ninject。我有以下问题。假设有两个api控制器(ControllerA和ControllerB)。两者都依赖于MyClass,而MyClass依赖于ClientFactory而ClientFactory依赖于Resolver。

public class MyClass
{
    public MyClass(IClientFactory clientFactory)
    { ... }
}

public interface IClientFactory
{
   Client CreateClient();
}

public class ClientFactory : IClientFactory
{
    private readonly IResolver _resolver;
    public ClientFactory(IResolver resolver)
    { 
        _resolver = resolver; 
    }

    ...
}

public class ResolverA : IResolver
{
}

public class ResolverB : IResolver
{
}

public ControllerA : ApiController
{
   public ControllerA(MyClass myClass)
   {
    ...
   }
}

public ControllerB : ApiController
{
    public ControllerB(MyClass myClass)
    {
       ...
    }
}

当MyClass注入ControllerB时,我想在ClientFactory中使用ResolverA,当MyClass注入到ControllerA中的ControllerA和ResolverB中。可以用Ninject配置吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

它可以(关键字是“上下文绑定”,在ninject wiki here中记录)。 但是,您的特定用例不支持开箱即用。有.WhenIsInjectedInto<T>,但这并不好,因为在您的情况下,直接父级始终为MyClass(您正在寻找类似.WhenHasAncestorOfType<T>()的内容)。 所以你必须自己动手:

kernel.Bind<IResolver>()
    .To<ResolverA>()
    .WhenAnyAncestorMatches(x => x.Binding.Service == typeof(ControllerA));

kernel.Bind<IResolver>()
    .To<ResolverB>()
    .WhenAnyAncestorMatches(x => x.Binding.Service == typeof(ControllerB));

当然,根据Controller实际请求的方式,您可能需要调整x.Binding.Service == typeof(...)部分。您还可以查看.WhenIsInjectedInto的实施,以获取想法/指导。