2011-10-10 54 views
2

我不能找到一種方法,在這種情況下注入參數:統一進樣參數beeing解決

class Top 
{ 
    private ISome some; 
    public Top() 
    { 
     some = CreateSome(localRuntimeVariable); 
    } 

    //I need to pass "some" instance as a InjectionParameter to Child constructor 
    [Dependency] 
    public Child Child {get;set;} 
} 
class Child 
{ 
    //I need to inject ISome but it can only be constructed in Top 
    public Child(ISome some, Foo foo) 
    { 
    } 
} 
public class Usage 
{ 
    private void Top GetTop(Foo foo) 
    { 
     return unity.Resolve<Top>(new DependencyOverride<Foo>(foo)); 
     //I expect: Top.Constuctor called and 'some' is assigned; 
     //   Top.Child property beeing resolved: Child.Constructor called 
     //   'foo' instance to be taken from unity.Resolve<Top>(new DependencyOverride<Foo>(foo)); 
     //   'some' instance to be taken from Top.some, but how to tell unity to inject it? 
    } 
} 
+0

解析語句在哪裏?在調用Resolve時已知哪些引用? – PVitt

+0

是的,我看到了這一行。但是在哪個上下文中調用?請把整個方法。調用解析時可以使用哪些引用? – PVitt

+0

@PVitt更新了問題。 –

回答

1
class Top 
{ 
    public Top(Foo foo, IUnityContainer container) 
    { 
     some = CreateSome(localRuntimeVariable); 
     Child = container.Resolve<Child>(new ParameterOverride("some" some), 
      new ParameterOverride("Foo", foo)); 
    } 

    public Child Child {get;private set;} 
} 

class Child 
{ 
    public Child(ISome some, Foo foo) 
    { 
    } 
} 

現在你可以解決上面的實例使用unity.Resolve<Top>(new ParameterOverride("Foo", foo))

不需要類UsageGetTop(Foo foo)只是語法糖unity.Resolve<Top>(new DependencyOverride<Foo>(foo))

+0

好吧,我的確寫得很好,但是這違反了我們應用程序的設計原則:DI容器只應用於組合根目錄(應用程序入口點),並且在構造函數中將DI容器作爲參數被認爲是我們團隊中的代碼味道。 –

+0

你的團隊如何解決你的問題? – PVitt

+0

他們沒有。我不會在這裏問一個問題,我的團隊中有人知道如何解決這個問題。 –