开发者

MEF Global CompositionContainer in existing applications

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开发者_如何学Go 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?


Is it a good practice to expose the CompositionContainer globally

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜