【发布时间】:2021-01-23 20:28:52
【问题描述】:
我在 Unity 中使用 C# 4.7.2 和 PRISM 6。
现在,在循环中需要 SomeClass 的实例。 Foreach 循环运行我需要 SomeClass 的新实例。通用实现类似于 MyMethod_CommonImplementation 中的代码。
如何在 DI 模式中正确实现该代码(在 MyMethod 中)?当然,我可以注入 UnityContainer 并使用 container.Resolve。但我相信这将是提供服务,而不是依赖注入。
该示例显示了一个循环进行五次运行。所以我可以注入 SomeClass 的五个实例。但这真的是正确的做法吗?
注册工作正常,顺便说一下,_exampleName 设置正确。
public class MyClass
{
IMyInterface _exampleName;
public MyClass(IMyInterface exampleName)
{
_exampleName = exampleName;
}
private void MyMethod()
{
for ( int index = 0 ; index < 5 ; index++ )
{
// at this place I want to "reset" the instance of _exampleName for each index
_exampleName.PropertyName = index
_exampleName.DoSomeImportantWork();
}
}
private void MyMethod_CommonImplementation()
{
for ( int index = 0 ; index < 5 ; index++ )
{
SomeClass exampleClassName = new SomeClass();
exampleClassName.PropertyName = index
exampleClassName.DoSomeImportantWork();
}
}
}
【问题讨论】:
-
你可以注入一个可以构建你需要的工厂
标签: c# dependency-injection unity-container