正在解析的属性的构造函数中的Unity Inject参数

时间:2011-10-10 13:32:11

标签: c# dependency-injection unity-container

在这种情况下,我找不到注入参数的方法:

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

1 个答案:

答案 0 :(得分: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))

解析top的实例

不需要课程UsageGetTop(Foo foo)只是unity.Resolve<Top>(new DependencyOverride<Foo>(foo))

的语法糖
相关问题