【发布时间】:2016-09-12 07:04:17
【问题描述】:
我正在转换我的代码以使用带有 StructureMap 的 IoC 容器。试图让我的头脑了解事物,我觉得它开始“点击”,我可以看到它对后端的意义何在。
但是,我正在努力工作,我发现了一些我不知道如何使它工作的情况。具体来说,我的原始构造函数使用并非真正依赖的参数做了重要的事情,或者在运行时会改变的事情。
假设我从这个(前 IoC 容器)开始,我在其中使用构造函数传递我的依赖项,但也向它发送一个 ImportantObject ,它依赖于运行时:
IMyPageViewModel myPageViewModel = new MyPageViewModel(importantObject, dialogManager, pageDisplay, viewModelProvider)
它正在构建它:
public MyPageViewModel(ImportantObject importantObject, IDialogManager dialogManager,IPageDisplay pageDisplay, IViewModelProvider viewModelProvider)
{
this.dialogManager = dialogManager;
this.pageDisplay = pageDisplay;
this.viewModelProvider = viewModelProvider;
importantObject.DoThatImportantThing();
}
现在,我正在迁移以使用 IoC 容器,起初我认为我应该这样做:
//I need to create an instance to use, so I use my IoC container:
IMyPageViewModel myPageViewModel = container.GetInstance<IMyPageViewModel>();
然后让它解决它的依赖关系,但是重要的对象是在运行时设置的。我无法将其注册为依赖项:
public MyPageViewModel(IDialogManager dialogManager,IPageDisplay pageDisplay, IViewModelProvider viewModelProvider, IContainer container)
{
this.dialogManager = dialogManager;
this.pageDisplay = pageDisplay;
this.viewModelProvider = viewModelProvider;
//however, here I have no access to the important object that I previously passed in my constructor
importantObject.DoThatImportantThing(); //obviously error
}
我想也许我应该使用“new”创建并传递 IoC 容器:
IMyPageViewModel myPageViewModel = new MyPageViewModel(importantObject, container)
然后让它在构造函数中解决它的依赖关系:
public MyPageViewModel(ImportantObject importantObject, IContainer container)
{
this.dialogManager = container.GetInstance<IDialogManager>();
this.pageDisplay = container.GetInstance<IPageDisplay>();
this.viewModelProvider = container.GetInstance<IViewModelProvider>();
importantObject.DoThatImportantThing();
}
但这让我觉得这不是一个好主意,具体来说,我不能使用测试寄存器运行它并让它创建一个虚拟/存根“MyPageViewModel”用于单元测试。
我能想到的唯一另一件事是从构造函数中删除所有逻辑并将其放入初始化方法或属性设置器中。然而,这意味着我必须确保在使用前总是调用初始化,它会隐藏错误/问题。
这些选项中的任何一个是否合理,我应该如何管理在具有依赖注入的构造函数中传递运行时依赖对象?
我试图远离静态工厂,因为我读过很多关于它们是反模式/不好的做法的文章。
编辑:为了回应布鲁诺·加西亚的回答,我决定使用工厂类型模式来保存容器并像这样处理对象创建:
class PageProvider : IPageProvider
{
public MyPageViewModel GetMyPage(ImportantObject importantObject)
{
//might just get, if it's a single only instance
return MyPageViewModel(ImportantObject importantObject,
container.GetInstance<IDialogManager>(),
container.GetInstance<IPageDisplay>(),
container.GetInstance<IViewModelProvider>())
}
}
【问题讨论】:
-
您能否进一步了解
ImportantObject类型和DoThatImportantThing方法?更具体地说,你为什么要这样做?IMyPageViewModel myPageViewModel = new MyPageViewModel(importantObject, container)线路现在在哪里? -
ImportantObject是如何创建的? -
根据我的经验,当您应用 DI 时,您将失去使用构造函数的能力。我对待另一种方法,如运行时构造函数(称为
Initialize或其他东西),它通常采用Id之类的方法从存储库中获取数据。您会丢失一些东西,例如只读属性,但对于 DI 设置恕我直言,这是非常值得的。 -
@Yacoub Massad 我有一个与特定模型相关联的 ViewModel(在这种情况下代表一艘船)。在构造函数中,它用作 ViewModelProvider 中的参数,它最终调用 WCF 服务以使用它用来操作的一堆数据填充原始对象。
-
@Nkosi 我正在尝试使用一个通用示例,因此我认为可以通过多种不同的方式创建它,我希望在实现 IoC 容器后,它将使用 GetInstance 创建
() 某处,所以我可以用测试存根替换 IImportantObject。
标签: c# dependency-injection structuremap