Back to list
Views:   21.5K
Replies:  1
Archived
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.
 
Hans Overkamp, Apr 27, 2010
Reply 1
I'm also interested in the answer to this, as I'm having the same issue.
Hector Sosa, Jun 05, 2010
Hi Dan Thanks for quick response. In today's environment there are application that need to integrate with different sites such as netflix, facebook, twitter, etc to provide better user experience and create new scenarios. MS has come up with OData protocol which is becoming standard across many sites. I would like to see what patterns need to be followed to build such app which can show the power of integration with multiple sites. Another item I wanted to add into the list was 'Windows Phone 7' UI. Looking forward for the next release. Regards Sanjay Singh
Apr 01, 2010
Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Licensing       EULA       Sitemap      
© Data & Object Factory, LLC.
Made with    in Austin, Texas