正确使用 Ninject NamedScope

Proper use of Ninject NamedScope

我很难理解 Ninject 的 NamedScope 模块应该如何工作。在我看来,每个(定义的)作用域都应该用于上下文化 "InNamedScope" 的绑定。

以这个玩具为例:

void Main()
{
    var kernel = new StandardKernel(new NamedScopeModule(), new ContextPreservationModule());

    kernel.Bind<ParentC>().ToSelf().WithConstructorArgument("name", "Name1").DefinesNamedScope("scope1");
    kernel.Bind<Intf>().ToConstant(new MyC() { ID = 1} ).InNamedScope("scope1");

    kernel.Bind<ParentC>().ToSelf().WithConstructorArgument("name", "Name2").DefinesNamedScope("scope2");
    kernel.Bind<Intf>().ToConstant(new MyC() { ID = 2 }).InNamedScope("scope2");

    kernel.GetAll<ParentC>().Dump();
}


public class Intf
{
    int ID { get; set; }
}


public class MyC : Intf
{
    public int ID { get; set; }
}

public class ParentC
{
    public ParentC(Intf[] c, string name)
    {
        this.C = c;
        Name = name;
    }

    public string Name { get; set; }
    public Intf[] C { get; set; }
}

对我来说,应该会产生这样的结果:

但是,我得到了一个异常:

UnknownScopeException: Error activating UserQuery+Intf The scope scope2 is not known in the current context.

我错过了什么?

在Ninject中,作用域与对象的生命周期有关。我将命名范围更多地视为将相同实例注入不同 类 的一种方式,如下所示:

public class Parent {
    public Parent(Child child, GrandChild grandChild) {}
}
public class Child {
    public Child(GrandChild grandchild) {}
}
public class GrandChild {}

kernel.Bind<Parent>().ToSelf().DefinesNamedScope("scope");
kernel.Bind<GrandChild>().ToSelf().InNamedScope("scope");

kernel.Get<Parent>();

注入 ParentgrandChild 与注入 Child.

的实例相同