Working with TypeCatalog in MEF

In MEF world, we use Types to define Export or Import. Catalogs are used to discover types in an assembly, Directory, or manually added types in TypeCatalogs. Today I will discuss how TypeCatalog works and how you can use it in your application.

TypeCatalog is actually a repository of Types that forms the basic Export and Import parts. MEF uses Types to discover the ExportAttribute and ImportAttribute in a ComposableContainer. When building a TypeCatalog you need to pass either an array of Types or an Enumerable of Types, which are used by the Catalog to form the Export Container. Lets take a look how it works with code :

public class ExportContainer
{
[Export]
public string ExportName { get; set; }

[Export]
public string GetName()
{
return this.ExportName;
}

[Export]
public Action MyActionDelegate { get; set; }

}

Here the class ExportContainer exports some of its members to the external world. When we pass this Type to a TypeCatalog, it forms a Part which exposes a the Exports(members marked with Export attribute) as a ExportDefinations and Imports(members marked with Import attribute) as ImportDefination. Hence if you do :

static void Main(string[] args)
{
TypeCatalog catalog = new TypeCatalog(typeof(ExportContainer));

Console.WriteLine(catalog.Parts.Count());

Console.ReadKey(true);
}

The console will print 1 as the number of Types that I have passed in the TypeCatalog is 1. You can pass as many Types in TypeCatalog constructor(as it takes params array) and each of the Type forms a part.

Finally in Debugger if you try to look into the Exports that are associated with the Part listed inside Catalog, you can check the ExportDefination to find them.

ExportsHere you can see the ExportDefination lists all the Exports that I pass to the Container. The ImportDefination on the other hand lists all the imports if we have defined it.

Finally we pass the catalog to ComposableContainer to compose parts.

Read more about it from the links :

Managed Extensibility Framework – A Look

Steps to write a plugin based application with MEF

Thank you for reading.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434

One Comment to “Working with TypeCatalog in MEF”

Comments are closed.