现有应用程序中的 MEF Global CompositionContainer
我正在研究 MEF 作为我们现有 .NET 应用程序中插件解析的解决方案。
在我能找到的所有示例中,主应用程序创建 CompositionContainer 的实例并调用 container.ComposeParts(this)。
问题是,我的应用程序并不完全基于 MEF 构建,因此对象图中存在一个没有 MEF 组件的漏洞。 所以我的对象层次结构可能如下所示:
应用程序(MEF容器)->对象B (无 MEF)->对象A(需要MEF 进口)
在此对象层次结构中,我不可能在应用程序上调用container.ComposeParts(this)并期望应用程序创建ObjectB并满足ObjectA的导入。
全局公开 CompositionContainer 是一个好习惯吗?这样我就可以在应用程序启动之后编写 ObjectA,或者我是否必须重构整个应用程序以支持线性 MEF 对象图?
I'm researching MEF as a solution to plug-in resolution in our existing .NET Application.
In all of the examples that I can find, the main application creates an instance of the CompositionContainer and calls container.ComposeParts(this).
The problem is, my application is not entirely built on MEF, so there is a hole in the object graph where there are no MEF components.
So my object hierarchy might look like this:
Application (MEF Container) -> ObjectB
(no MEF) -> ObjectA (requiring MEF
Imports)
In this object hierarchy, it's impossible for me to call container.ComposeParts(this) on the application and expect the application to create ObjectB and satisfy ObjectA's Imports.
Is it a good practice to expose the CompositionContainer globally so I can compose ObjectA at a later time than on Application Startup or do I have to restructure my entire application to support a linear MEF object graph?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不认为这是一个好的实践,但当不可能在所有地方引入控制反转原理时,这是一个合理的妥协。有时现有的代码库并不完全在您的控制之下,或者是.NET 和本机代码的复杂组合(例如COM 组件),或者只是太大而无法重构。
在 Silverlight 中,从 XAML 构造对象也不受 MEF 的控制,因此 Microsoft 引入了本质上相同的解决方案:默认的 MEF 容器可作为全局访问,并使用
PartInitializer.SatisfyImports(this);
进行调用>。请注意,遵循此模式会将全局的任何使用者紧密耦合到 MEF 以及用于公开它的全局变量。无法在其他应用程序或其他 IoC 容器中按原样重用此代码。它还将使单元测试变得复杂。
I wouldn't call it a good practice, but it is a reasonable compromise when it is impossible to introduce the inversion of control principle for construction everywhere. Sometimes the existing codebase is not entirely under your control, or a complex mix of .NET and native code (e.g. COM components), or simply too large to refactor.
In Silverlight, the construction of objects from XAML is also outside the control of MEF, so Microsoft introduced essentially the same solution: the default MEF container is accessible as a global and invoked with
PartInitializer.SatisfyImports(this);
.Note that following this pattern will tightly couply any consumers of the global to MEF and the global variable used to expose it. It will not be possible to reuse this code as-is in other applications or with other IoC containers. It will also complicate unit testing.