MEF exception "'SourceProvider' must be set."

I play with the new System.ComponentModel.Composition namespace in .NET 4.0 beta 2, also known as the Managed Extensibility Framework .

I use the following C # example where Monkey imports Banana :

 public interface IBanana { } [Export(typeof(IBanana))] public class Banana : IBanana { } public class Monkey { [Import(typeof(IBanana))] public IBanana Banana { get; set; } } 

However, when I try to compose a monkey as follows, I get an InvalidOperationException message with the message " This object has not been initialized - the" SourceProvider "property must be set. ":

 var exportProvider = new CatalogExportProvider(new TypeCatalog(typeof(Banana))); var container = new CompositionContainer(exportProvider); var monkey = new Monkey(); container.ComposeParts(monkey); 

What am I missing here? I know that I can transfer the directory directly without wrapping it in CatelogExportProvider, but should it not work above?

+4
source share
1 answer

CatalogExportProvider needs access to the container. The following code should work:

 var exportProvider = new CatalogExportProvider(new TypeCatalog(typeof(Banana))); var container = new CompositionContainer(exportProvider); exportProvider.SourceProvider = container; var monkey = new Monkey(); container.ComposeParts(monkey); 

The container does this automatically when you pass the directory to the constructor. I do not think that there is often a reason to create a CatalogExportProvider manually.

The reason CatalogExportProvider needs a reference to the container is because there may be parts with imports in the catalog that must be satisfied by other export providers with which the container is connected.

+5
source

All Articles