在这种情况下,我找不到注入参数的方法:
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 :(得分: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))
不需要课程Usage
。 GetTop(Foo foo)
只是unity.Resolve<Top>(new DependencyOverride<Foo>(foo))