Sunday, April 29, 2012

MEF (Managed Extensibility Framework), .NET 4, Dependency Injection and Plug-in Development

Almost after .Net 4 was released I remember reading about MEF (Managed Extensibility Framework), this was a framework for developers to compose their application with required dependencies. At first this looks like the Unity Container used for dependency injection, but MEF is much more than a dependency container but there is nothing stopping you from using MEF as a dependency injector.

I remember around 5 years back when I was in a project that created a framework that allows developers to plug-in there modules as WinForm screens. The developer would create a set of screens with the intended functionalities and the drop this component in the bin folder of the framework and then will move on to do some painful configurations for the framework to pick up the module. Dropping the component into the bin folder and doing a bit of configuration is all that s needed for the framework to pick up display the screens. Typically, the configurations would also contain metadata about the screen.

Although in this model, plugging in a component is easier, there is of course the pain of creating and testing the framework. This is where MEF comes in, MEF allows developers to create and consume components (known as parts) through an attributed model, and what’s more MEF comes as part of .Net 4.0 . Let me take a simple scenario, say your application needs to request third party services like ProductService or CustomerService based on dynamic requests. Let’s say you have created adapters for ProuctService and CustomerService and the ServiceManager class is responsible for mediating the service calls.

MEF works with the concept of imports and exports, if you have a property that you want MEF to inject, in our example the set of adapters, this field becomes an Import where as the adapter it self become the export.

The adapters would look like this…

   [Export(typeof(IAdapter))]
public class ProductserviceAdapter : IAdapter
{
public object Invoke(object data)
{
return "From Product";
}
}
And
[Export(typeof(IAdapter))]
public class CustomerServiceAdapter : IAdapter
{
public object Invoke(object data)
{
return "From Customer";
}
}

In the code above, both our adapters implements the contract IAdapter, the Export attribute on top of the class tells MAF that this class can be used to satisfy an import for the contract of IAdapter.

The ServiceManager class would be like this…

   public class ServiceManager
{
[ImportMany]
private IEnumerable<IAdapter> adapters;
}

The ServiceManager class contains reference to IEnumerable, this is the reference we want MEF to fill for us. Note this reference has been marked with the ImportMany attribute. By default ImportMany will take the type of the property that it decorates, in this case IAdapter, or else you would need to explicitly pass in the type of the contract that you want to import into the constructor of ImportMany.

Now let’s wire up the adapters instance variable with the CustomerAdapter and the ProductAdapter. You can do this like this...assuming that both the adapters reside in the same assembly as the ServiceManager, I can do this…

    static CompositionContainer container;
private static void SetupPart(ServiceManager manager)
{
if (container == null)
{
container =
new CompositionContainer(new AssemblyCatalog(typeof(ServiceManager).Assembly));
}
container.ComposeParts(manager);
}

First we are creating a CompositionContainer, this is the container that will manage the life time of the components that it imports. An AssemblyCatalog is passed into the container, the catalog has information of where to find your imports, for an example, the adapters may have been dropped into a separate directory, we can tell MEF to search a particular directory by passing in DirectoryCatalog. In this case we are passing in the assembly name where the adapter can be found. You can search in both these places by adding both these catalogs into an AggregateCatalog and passing that into the container.

Next the ComposeParts method takes in the instance which we want to wire up Imports, in our case we want to fill in the adapters inside the ServiceManager class. So, we pass the ServiceManager instance into the ComposeParts method. This method would search in the assembly that we added in the catalog and would try to find any class the exposes itself as an Export for the contract IAdapter. One catch on the ComposeParts method is that it resides as an extension method in the namespace System.ComponentModel.Composition. Now if you try to access the adapters instance variable inside the ServiceManager instance, you will see that it contains the ProductAdapter and the CustomerAdapter.

Ways of importing

In our example above, our adapters instance variable is a IEnumerable, if you want to Import only one instance of a component you could do this…

     [Import]
private IAdapter adapter;

In this example, if MEF find more than one export for IAdapter, it will throw an error. It will also throw an error if no export is found at all. You can use default values for imports like this..

    [Import(AllowDefault=true)]
private IAdapter adapter;

The allow default parameter specifies that MEF should not throw an exception if it does not find matching exports instead, set the value to null.

You can also, import the adapters as Lazy components, like this…

     [ImportMany]
private IEnumerable<Lazy<IAdapter>> adapters;

In this case adapters will be loaded only when the Value property of the Lazy instance is invoked.

There might be cases where the Adapter that is being exported itself as a dependency with another class say CommonConfigurationProvider, you can specify this as an Import in the export component itself, in our case the ProductAdapter…Our code would look like this…

   [Export(typeof(IAdapter))]
public class ProductserviceAdapter : IAdapter
{
public object Invoke(object data)
{
return "From Product";
}
[Import]
public CommonConfigProvider Provider
{
get;
set;
}
}

Now as long as there is a an export matching the type CommonConfigProvider, the import for the Provider property in the ProductAdapter will be filled when the ProductAdapter is being exported in the ServiceManager class. So if the CommonConfigProvider has an import declaration within it (another dependency), that will also be filled, this means MEF imports are recursive.

Metadata

Most of the time the when imports are loaded, you would want to use only specific component according to certain metadata approached to the component. For an example, when a request for the ProductService comes is, you would want to send the request to the correct component, i.e to the ProductAdapter. MEF allows you to attach metadata to your exports, so for an example, I can attach metadata to the ProductAdapter like this.

   [Export(typeof(IAdapter))]
[ExportMetadata("ServiceName", "ProductService")]
public class ProductserviceAdapter : IAdapter
{
public object Invoke(object data)
{
return "From Product";
}
}

The ExportMetadata takes in a key value pair to define metadata, in our example, we define a key called ServiceName and gives it a value “ProductService”

To get the metadata, you need to use Lazy for the import, so you would define your import like this…

     [ImportMany]
private IEnumerable<Lazy<IAdapter, IAdapterMetadata>> adapters;

In the above code snippet, AdapterMetadata is an interface that defines a property to get the service name.

     public interface IAdapterMetadata
{
string ServiceName { get; }
}

When MEF imports components, it’s going to create a class dynamically that implements the IAdapter interface and set the values of the metadata set in the ExportMetadata attribute as property values of this dynamically generated class. Hence, you can now send the request to the ProductService like this…

 IAdapter adapter = adapters.
Where(a => a.Metadata.ServiceName == "ProductService")
.Single().Value;

Life time management

The ComposeParts() method composes all imports for an instance, by default the composed parts are shared and container managed, if you want this to be changed to per call you can do this by adding a PartCreationPolicy attribute..

   [Export(typeof(IAdapter))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class CustomerServiceAdapter : IAdapter
{
public object Invoke(object data)
{
return "From Customer " ;
}
}

You can remove parts from the container through the ReleaseExport method in the container, you can also do a composition without attaching the components to the container like this..

 container.SatisfyImportsOnce(manager);

MEF can be used as a dependency injection container; however, MEF provides more functionalities then Unity. There are good reasons to use MEF as it continues to evolve. .Net 4.5 upgrades MEF to use convention based than attribute based. That’s all I have time for this weekend.

No comments:

Post a Comment