Unity 在正在解析的属性的构造函数中注入参数
我找不到在这种情况下注入参数的方法:
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?
}
}
I can't find a way to inject parameters in this scenario:
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?
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
现在,您可以使用
unity.Resolve(new ParameterOverride("Foo", foo))
解析 top 的实例,不需要
Usage
类。GetTop(Foo foo)
只是unity.Resolve(new DependencyOverride(foo))
的语法糖Now you can resolve an instance of top using
unity.Resolve<Top>(new ParameterOverride("Foo", foo))
The class
Usage
isn't needed.GetTop(Foo foo)
is just syntactic sugar forunity.Resolve<Top>(new DependencyOverride<Foo>(foo))