Search code examples
c#mefioc-container

Export a property using MEF


Let us consider the following scenario:

class Master
{
    private Person selectedPerson;

    public Person SelectedPerson
    {
        get
        {
            return selectedPerson;
        }
        set
        {
            selectedPerson = value;

        }
    }

}

[Export(typeof(Details))]
class Details
{
    [ImportingConstructor]
    public Details(Person person)
    {

    }
}

I need to initialise an instance of Details with SelectedPerson as argument. So, basically, I need to inject a particular instance of Person to the Details constructor.

How can I do that using MEF?


Solution

  • Simple answer: You need to export the Person you want to inject. Here is a basic example of a possible console application:

    public class Program
    {
        [Export(typeof(Person))]
        private Person personToInject { get; set; }
    
        public static void Main(string[] args)
        {
            new Program().Run();
        }
    
        private void Run()
        {
            var catalog = new DirectoryCatalog(".");
            var container = new CompositionContainer(catalog);
    
            //Create the person to inject before composing
            personToInject = new Person();        
    
            container.ComposeParts(this);
        }
    }
    

    Note that the ImportingConstructor attribute is only allowed to use once a class.

    To improve the solution you should use names to identify the properties to inject. Therefore you have to extend the prototype of your constructor

    [ImportingConstructor]
    public Details([Import("personParameter")]Person person)
    

    and your export

    [Export("personParameter")]
    private Person personToInject { get; set; }