MEF configuration

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

If everything is in the code, what are the examples of transitions between the various classes that are involved in exporting? that is, if class A and class B both export IMyExport, what are some good ways to "tune" an application to use A or use B?

+5
source share
1 answer

As far as I know, MEF does not have a configuration file. In case you want your application to use one implementation over another, you could create a new ConfigurationCatalogone that will receive the configuration file as input and will export only those parts that it reports. It is possible that something similar already exists in MefContrib , so I would check there.

In addition, it is up to the classes themselves to decide which implementation they would like to use. One possible way to achieve the desired result is to use contract names.

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

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

Then, the importing class IMyExportcan indicate which part it wants to use.

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

, IMyExport , . , .

[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
    }
}
+7

All Articles