Monday, April 12, 2010

The Managed Extensibility Framework (MEF) More on Part Creation Policies -- Enter the ExportFactory

Last I blogged about part creation polices and why it might be a good idea to not say anything about them, and leave them as their default, "Any". This time I'm gonna talk about the ExportFactory which is what you'll wanna use for your object factory needs in the future.

Unfortunately, the ExportFactory didn't make it into the .NET 4.0 RTM build and that's a darn shame. However, MEF being open source and all, allows one to easily rectify the problem.

You can find all relevant source here. It contains a link to compiled binaries for several .NET Framework versions and source code that you can drop into any existing framework/core assembly you have. I've done this with the .NET 4.0 RC version of MEF without much of a problem. But you'll need to configure your CompositionContainer some more.

var catalog = ... // get a catalog here
var exportFactoryProvider = new Microsoft.ComponentModel.Composition.Hosting.ExportFactoryProvider();
container = new CompositionContainer(catalog, exportFactoryProvider);
exportFactoryProvider.SourceProvider = container; // a bit odd, but necessary

The ExportFactory is used in the same way as the Lazy<T,TMetadata> type and will create instances when you ask for them. This conveniently avoids the hassle of having to manually compose objects created through the common factory pattern. The instances served by the ExportFactory will already have it's imports satisfied, so no additional steps are required. MEF makes it fun!

e.g.

[ImportMany]
public ICollection<ExportFactory<IMyObject, IMyObjectMetadata>> Objects { get; private set; }

I ran into problems when using constructor injection, if you follow the link above you'll find out how I worked around that.

No comments: