Working with MEF

MEF applications are based around a small set of core concepts: the composition container, catalog, and parts. These are both abstract concepts and a physical API that you can interact with from managed code. All the MEF classes live within the System.ComponentModel.Composition namespace and its children namespaces, such as System.ComponentModel.Composition.Hosting.

Parts

An MEF part is the primary unit of functionality. Parts have a set of features they provide (called exports); parts might also depend on features that other parts provide (termed imports).

Parts verbalize their exports and imports through contracts. At the code level, contracts are specified by using declarative attributes to declare their imports and exports (System.ComponentModel.Composition.ImportAttribute and System.ComponentModel.Composition.ExportAttribute, respectively).

Here is an example of a C# class declaring an export.

[Export(typeof(IMyExtensionProvider))]
internal class TestExtensionProvider

Composition Container

The composition container is the core of an MEF application that does all the heavy lifting. It holds all the available parts, handles the instantiation of those parts, and is the primary composition engine in MEF. In this context, composition can be thought of as the process of matching required services (imports) with published services (exports).

Host applications can instantiate a container via the System.ComponentModel.Composition.Hosting.CompositionContainer class like this:

private CompositionContainer _container;

Catalog

The catalog is a sort of Registry and discovery mechanism for parts that the composition container uses. MEF provides a default set of catalogs, each one designed to discover parts from a particular source or target. There is a type catalog for discovering parts from a given .NET type (via the TypeCatalog class), an assembly catalog for discovering parts from an assembly (via the AssemblyCatalog catalog), and a directory catalog (via the DirectoryCatalog class) for discovering parts that exist in a specified folder.

A fourth class, AggregateCatalog, enables you to combine multiple catalogs so that parts from multiple catalog sources can be combined into one master catalog.

A catalog instance can be passed into the constructor for a CompositionContainer object. You could write the following code to both create a new composition container and specify a catalog of parts that are to be discovered from within the specific assembly.

var catalog = new TypeCatalog(typeof(MyExtension));

CompositionContainer container =
   new CompositionContainer(catalog);

Figure 16.1 shows a diagram of the abstract MEF architecture.

Image

FIGURE 16.1 A simplified view of the MEF architecture.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset