使用Ninject注入类库,其中构造函数采用多个参数

时间:2014-01-20 10:48:36

标签: c# inversion-of-control ninject

我正处于Ninject困境之中。另外,如何从我的C#解决方案中的多个区域绑定到同一个容器。总而言之,我知道通过Ninject Modules加载是最好的方法,但我无法直接访问内核(这是我理解的,反无论是反模式)来调用{{ 1}}。

所以我相信构造函数注入是最好的方法。现在假设我有顶级类_kernel.Get<T>(),它会加载Program

Module : NinjectModule

为了将代码保持在最低限度,假设ClassA模块将class Program { IKernel _kernel; public static main() { _kernel = new StandardKernel(); _kernel.Load(ClassA.Module); _kernel.Load(ClassB.Module); } } 的所有实现与ISomething绑定,ConcreteSomething(其中ClassB依赖于此实现)实现以下内容构造方法;

ClassA

在单个解决方案中,可以直接访问_kernel,public ClassB(ISomething thing, int paramA, int paramB) { //Do stuff with paramA and paramB using thing }

但是,我不确定如果提供类无法访问其调用者容器,这将如何工作。

我想到的一个想法是使用工厂方法,但我不知道这是如何工作的。

任何重量都会受到赞赏。

1 个答案:

答案 0 :(得分:1)

对于依赖项使用构造函数注入是正确的。

如何将参数(paramA,paramB)移动到方法,如Initialize或Execute?

如果这不合理(比如当它的命令),那么你将需要使用工厂。 看看https://github.com/ninject/ninject.extensions.factory

对于工厂扩展不支持的用例,您始终可以拥有一个可以注入IResolutionRoot的工厂。你可以做Get&lt;&gt;在那个界面上。工厂可以驻留在任何组件中。

public class FactoryB : IFactoryB {
    private readonly IResolutionRoot resolutionRoot;
    public FactoryB(IResolutionRoot resolutionRoot) {
        this.resolutionRoot = resolutionRoot;
    }

    public IClassB Create(int paramA, int paramB) {
        return this.resolutionRoot.Get<IClassB>(new ConstructorArgument("paramA", paramA), new ConstructorArgument("paramB", paramB));
    }
}

我不知道你是否真的需要为paramA paramB使用工厂。这取决于价值来自何处或如何确定。它们是依赖于classA还是仅仅是“全局配置”值?