2017-10-09 39 views
1

我很難理解Ninject的NamedScope模塊應該如何工作。在我看來,每個(定義的)作用域都應該用來描述「InNamedScope」的綁定。正確使用Ninject NamedScope

有了這個玩具的例子:

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; } 
} 

對我來說,應該產生這樣的:

enter image description here

但是,相反,我得到一個exeception:

UnknownScopeException:錯誤激活UserQuery + Intf 範圍scope2不是在當前情況下是已知的。

我錯過了什麼?

回答

1

在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>(); 

grandChild作爲注入Child注入Parent是相同的實例。

+0

這很有道理,我想我誤解了ninject範圍的目的。有什麼擴展可以完成我想要完成的任務嗎?或者我應該使用'Named(..)'和'WhenAnyAncestorNamed(..)' –

+0

是的,'Named(...)'和'WhenAnyAncestorNamed(...)'可能適用於此。你的玩具示例讓我想起另一個SO問題,https://stackoverflow.com/questions/43864334/ninject-binding-a-tree-of-data,並且建議使用Ninject來綁定組件圖,而不是數據中心對象。 –

+0

同意..這只是爲了簡化示例,我真正的問題是試圖使用不同的綁定(到不同的類)使用NamedScope。感謝您的幫助。 –