简体   繁体   English

在Ninject中注入相同类型的多个参数

[英]Injection of multiple parameters of the same type in Ninject

Lets say we have a class X like this: 可以说我们有一个这样的X类:

class X
{
   X(Z a, Z b)
   { }
}

And the Z class would have a Y dependency: Z类将具有Y依赖项:

class Z
{
   Z(Y c)
   { }
}

What's the proper way to bind these classes such that two instances of Z, each of them with a different instance of Y, get injected into X? 绑定这些类的正确方法是什么,以便将两个Z实例(每个都有一个不同的Y实例)注入X?

I know these have to do with Context Binding, but I'm not sure how to go about it. 我知道这些与上下文绑定有关,但是我不确定该怎么做。

EDIT: 编辑:

The Y class would be: Y类为:

class Y
{
    Y(string someString)
    { }
}

I want the two instances of Y with a different string as well. 我也希望Y的两个实例具有不同的字符串。

Thanks 谢谢

You could used Named Bindings . 您可以使用命名绑定 Other types of contextual bindings can be found here . 其他类型的上下文绑定可以在这里找到。

Bind<X>().To<XA>().Named("A");
Bind<X>().To<XB>().Named("B");

public class Z {
    public Z([Named("A")] X x1, [Named("B")] X x2) {}
}

If your bindings for X and Y are not scoped, then each time an X object is requested from the kernel, it will get constructed with two unique Z objects (each having a unique instance of Y). 如果您对X和Y的绑定没有作用域,那么每次从内核请求一个X对象时,它将使用两个唯一的Z对象(每个对象都有一个唯一的Y实例)构造。 This will happen by default. 默认情况下会发生这种情况。

pass your dependencies that implement the same interface as an IEnumerable. 传递实现与IEnumerable相同的接口的依赖项。 Otherwise, Ninject will yell at you if you have multiple bindings for one interface. 否则,如果一个接口有多个绑定,Ninject会大喊大叫。 Use the .WithConstructorArgument() method to define your string. 使用.WithConstructorArgument()方法定义您的字符串。 If the string is not constant, you can use .ToMethod() instead and have the string determined at runtime. 如果字符串不是常量,则可以改用.ToMethod()并在运行时确定字符串。

public class Z
{
    public Z(IEnumerable<Y> dependencies)
    {
        if (dependencies == null) throw new ArgumentNullException("dependencies");
        _dependencies = dependencies;
    }
}

static void Main() // or other entry point
{
    var kernel = new StandardKernel();
    kernel.Bind<Z>().To<ZImplementation>();
    kernel.Bind<Y>().To<YImplementation1>().WithConstructorArgument("c", "string to inject 1");
    kernel.Bind<Y>().To<YImplementation2>().WithConstructorArgument("c", "string to inject 2");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM