Satisfying imports for an existing facility using MEF

Given an arbitrary existing object that is attributed with [Import] tags, what do I need to do for a tambourine dance to get the MEF to fill in the import?

Most of the documentation on the blog seems to be built against the preliminary versions of MEF and no longer works - I use the released part of .NET 4.0 (or, alternatively, MEF 2.0 Preview 3).

AggregateCatalog _catalog; CompositionContainer _container; public void Composify(object existingObjectWithImportTags) { lock(_container) { var batch = new CompositionBatch(); // What do I do now?!?! } } 
+6
c # mef
source share
2 answers

MEF permits Import (via injection of properties or constructor) along with their own dependencies on exported types in registered registers registered in the directory (including the current assembly).

If you want to create an object directly (using the new keyword), or if the export was not ready at the time of creation, you can use the container to satisfy the import of the object using:

 _container.SatisfyImportsOnce(yourObject); 

I put together a small script doing just that. here is the code:

 public class Demo { private readonly CompositionContainer _container; [Import] public IInterface Dependency { get; set; } public Demo(CompositionContainer container) { _container = container; } public void Test() { //no exported value, so the next line would cause an excaption //var value=_container.GetExportedValue<IInterface>(); var myClass = new MyClass(_container); //exporting the needed dependency myClass.Export(); _container.SatisfyImportsOnce(this); //now you can retrieve the type safely since it been "exported" var newValue = _container.GetExportedValue<IInterface>(); } } public interface IInterface { string Name { get; set; } } [Export(typeof(IInterface))] public class MyClass:IInterface { private readonly CompositionContainer _container; public MyClass() { } public MyClass(CompositionContainer container) { _container = container; } #region Implementation of IInterface public string Name { get; set; } public void Export() { _container.ComposeExportedValue<IInterface>(new MyClass()); } #endregion } 

Now just use new Tests(new CompositionContainer()).Test(); to start the demo.

Hope this helps :)

+6
source share
 _container.ComposeParts(existingObjectWithImportTags); 

ComposeParts is the extension method you are looking for.

It just creates a CompositionBatch and calls AddPart (AttributedModelServices.CreatePart (attribitedObject)) and then calls _container.Compose (batch).

+3
source share

All Articles