【发布时间】:2017-04-11 13:53:42
【问题描述】:
我正在尝试掌握 IoC 容器(目前特别是 Unity),并且对于预先注入所有依赖项的概念有些挣扎。
我的问题与具有构造函数参数的类特别相关,当我最初在容器中注册类型时,该参数的值是未知的。
这里有一个小sn-p,应该能说明我在说什么。
class Class1
{
IUnityContainer uContainer;
public Class1()
{
uContainer = new UnityContainer();
uContainer.RegisterType<IRepo, Repo>(new ContainerControlledLifetimeManager()));
Class2 cls2 = uContainer.Resolve<Class2>();
cls2.DoSomething();
}
}
class Class2
{
IRepo _repo;
public Class2(IRepo p_repo)
{
_repo = p_repo;
}
public void DoSomething()
{
IType2 typ2 = new Type2(_repo.SomeDataRetrieved());
Class3 cls3 = new Class3(_repo, typ2);
}
}
class Class3
{
IRepo _repo;
IType2 _type2;
public Class3(IRepo p_repo, IType2 p_type2)
{
_repo = p_repo;
_type2 = p_type2;
}
}
我可以在 Class1 中设置容器,并使用 UnityContainer 将 Repo 注入 Class2。在 Class2 中,对 Repo 的一些查找是返回一个 Type2 的实例,该实例只能在 Class2 中实例化。然后我需要将 Repo 与 Type2 创建的新对象一起传递给 Class3。
问题是双重的:
- 我无法解析 Class1 中的 Class3,因为它只能在 Class2 中实例化。
- 我无法在容器中注册 Type2,因为它实际上必须有一个基于 Class2 中的调用输出的值(不是默认值),该值与 Container 存在并执行的范围不同注册。
就目前而言,我可以使用容器将依赖项注入 Class2,但对于 Class3,我需要创建新实例或使用从 2 到 3 的构造函数注入,这让我想知道为什么我要使用容器然后如果无论如何,我不得不求助于手动注射。
那么,如何在容器中注册 Class3,以便在实例化它时,注入一开始在容器中注册的 repo 的单例以及在 DoSomething 中创建的 Type2 的实例。
提前感谢您的帮助。
【问题讨论】:
标签: c# dependency-injection unity-container