gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:11:32 25 4
gpt4 key购买 nike

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

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

最佳答案

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 的实例

类(class)Usage不需要。 GetTop(Foo foo)只是 unity.Resolve<Top>(new DependencyOverride<Foo>(foo)) 的语法糖

关于c# - 正在解析的属性构造函数中的 Unity Inject 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7713537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com