Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MEF Configuration

Tags:

c#

c#-4.0

mef

Are there any configuration file settings for MEF, or is everything done in code?

If everything is in code, what are some best practices for switching between different classes that do exports? i.e. if Class A and Class B both export IMyExport, what are some good ways to "configure" the app to use A or to use B?

like image 501
Fernando Avatar asked Jul 20 '12 19:07

Fernando


1 Answers

As far as I know, MEF doesn't have a configuration file. In the case that you want your application to use one implementation over the other, you could possibly create a new ConfigurationCatalog which will get a configuration file as an input and will only export the parts it tells it to. It's possible that something like that already exists in MefContrib, so I would check there.

Other than that, it's up to the classes themselves to decide which implementation they'd like to use. One possible way to achieve what you want is by using contract names

[Export("My Contract Name", typeof(IMyExport))]
public class A : IMyExport { }

[Export("Another Contract Name", typeof(IMyExport))]
public class B : IMyExport { }

Then the class importing IMyExport can specify which of the parts it wants to use

[Import("Another Contract Name")]
public IMyExport MyExport { get; set; }

If you know that a certain dependency IMyExport can be exported more than once, you can add metadata to the export and decide at runtime which of the exports you'd like to use according to its metadata. If you go with that direction, your code would look something like this

[MySpecialExport(SomeData = "ABC")]
public class A : IMyExport { }

[MySpecialExport(SomeData = "DEF")]
public class B : IMyExport { }

public class MyClass
{
    [ImportMany(typeof(IMyExport))]
    public IEnumerable<Lazy<IMyExport, IMyExportMetadata>> MyProperty { get; set; }

    public void DoSomething()
    {
        var myLazyExport = MyProperty.FirstOrDefault(x => x.Metadata.SomeData == "DEF");
        IMyExport myExport = myLazyExport.Value;

        // Do something with myExport
    }
}
like image 56
Adi Lester Avatar answered Sep 20 '22 03:09

Adi Lester