Skip to main content

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.

Comments

Popular posts from this blog

Hosting WCF services on IIS or Windows Services?

There came one of those questions from the client whether to use II7 hosting or windows service hosting for WCF services. I tried recollecting a few points and thought of writing it down. WCF applications can be hosted in 2 main ways - In a Windows service - On IIS 7 and above When WCF was first released, IIS 6 did not support hosting WCF applications that support Non-HTTP communication like Net.TCP or Net.MSMQ and developers had to rely on hosting these services on Windows Services. With the release of IIS 7, it was possible to deploy these Non-Http based applications also on IIS 7. Following are the benefits of using IIS 7 to host WCF applications Less development effort Hosting on Windows service, mandates the creating of a Windows service installer project on windows service and writing code to instantiate the service, whereas the service could just be hosted on IIS by creating an application on IIS, no further development is needed, just the service implementa

The maximum nametable character count quota (16384) has been exceeded

Some of our services were growing and the other day it hit the quote, I could not update the service references, nor was I able to run the WCFTest client. An error is diplayed saying " The maximum nametable character count quota (16384) has been exceeded " The problem was with the mex endpoint, where the XML that was sent was too much for the client to handle, this can be fixed by do the following. Just paste the lines below within the configuration section of the devenve.exe.config and the svcutil.exe.config files found at the locations C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE , C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin Restart IIS and you are done. The detailed error that you get is the following : Error: Cannot obtain Metadata from net.tcp://localhost:8731/ Services/SecurityManager/mex If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the specified address. F

ASP.NEt 2.0 Viewstate and good practices

View state is one of the most important features of ASP.NET because it enables stateful programming over a stateless protocol such as HTTP. Used without strict criteria, though, the view state can easily become a burden for pages. Since view state is packed with the page, it increases size of HTTP response and request. Fortunately the overall size of the __VIEWSTATE hidden field (in ASP.NET 2.0) in most cases is as small as half the size of the corresponding field in ASP.NET 1.x. The content of the _VIEWSTATE field (in client side) represent the state of the page when it was last processed on the server. Although sent to the client, the view state doesn't contain any information that should be consumed by the client. In ASP.NET 1.x, if you disable view state of controls, some of them are unable to raise events hence control become unusable. When we bind data to a grid, server encodes and put whole grid in to view state, which will increase size of view state (proportional to the