Home  /  Questions  /  Question



100   96.6
Apr 27, 2010


How do I use constructor dependency injection in MEF?

So, here is a questions about the newly released MEF 4.0 (Managed Extension Framework).
In MEF you can use the ImportingConstructor attribute to decorate a contructor, like so: 
class Test
{
   [ImportingConstructor]
   public Test(IMessageSender messageSender) 
   {
   }
}
However, I am not able to find example code that actually resolves this Import. 

There are plenty of composition examples like below: 

private void Compose()
{
    var catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
    var container = new CompositionContainer(catalog);
    container.ComposeParts(this);
}
It composes parts of this, meaning the instance has already been already constructed.


Alternatively, you may find code like so:  

  var catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());
  var container = new CompositionContainer(catalog);
  
  Employee employee = new Employee()
  container.ComposeParts(employee);
But again, the constructor of Employee has already been called before composition takes place.



My question is this: how do you let MEF invoke the constructor (i.e. create an object) of an Imported constructor?

I would have expected something like: 
container.CreateObject("name" or type)
Any pointers will be greatly appreciated.
 



340   99.9
Jun 05, 2010
I'm also interested in the answer to this, as I'm having the same issue.
 1 comment
 
In order to have MEF create the part you have to do a few things. 1. The part itself has to have an Export on it. Which you would achieve by adding an [Export] attribute to the class. 2. If the part is in Silverlight it must be public, otherwise private is fine. 3. You pull on the container to create the part. a. You can pull on it directly by calling container.GetExportedValue(); b. You can ask the container for a part which imports Test. (using GetExportedValue) c. You call SatisfyImportsOnce/ComposeParts (or CompositionInitializer.SatisfyImports on Silverlight) on an instance that imports Test. Cheers --- Glenn Block  Dec 29, 2010