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.
Here 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.
Pingback: Working with AssemblyCatalog in MEF - Daily .Net Tips