gpt4 book ai didi

c# - Unity Framework - 将整数和字符串传递到已解析的对象中

转载 作者:行者123 更新时间:2023-11-30 15:11:06 25 4
gpt4 key购买 nike

有没有办法使用 Unity 框架将整数作为参数传递给构造函数或已解析的对象?

伪代码..

IService svc = Container.Resolve<ConcreteService>()

在这种情况下,具体服务将是这样的......

public class ConcreteService
{
public ConcreteService(int val)
{
}
}

我还需要在 xml 配置中执行此操作,而不是在代码中执行此操作。

提前致谢。

最佳答案

希望我没听错

   public class ConcreteService {

public int Val { get; set; }

public ConcreteService(int val) {
Val = val;
}
}

现在让我们配置 unity。

        var container = new UnityContainer();

container.RegisterType<ConcreteService>();
container.Configure<InjectedMembers>().ConfigureInjectionFor<ConcreteService>(new InjectionConstructor(1));

container.RegisterType<ConcreteService>("for42");
container.Configure<InjectedMembers>().ConfigureInjectionFor<ConcreteService>("for42",
new InjectionConstructor(42));
container.RegisterType<ConcreteService>("for31");
container.Configure<InjectedMembers>().ConfigureInjectionFor<ConcreteService>("for31",
new InjectionConstructor(31));

Debug.WriteLine(container.Resolve<ConcreteService>().Val); //1
Debug.WriteLine(container.Resolve<ConcreteService>("for42").Val); //42
Debug.WriteLine(container.Resolve<ConcreteService>("for31").Val); //31

“for42”的等效配置是

统一 1.4

<type type="ConcreteService"  name="for42">
<typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement,
Microsoft.Practices.Unity.Configuration">
<constructor>
<param name="val" parameterType="int">
<value value="42"/>
</param>
</constructor>
</typeConfig>
</type>

统一 2.0

大同小异但没有多余的typeConfig节点

<type type="ConcreteService"  name="for42">
<constructor>
<param name="val" parameterType="int">
<value value="42"/>
</param>
</constructor>
</type>

关于c# - Unity Framework - 将整数和字符串传递到已解析的对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2720015/

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