Mef imports all types that implement the interface specified at runtime.

Can I write a class to use mef to import all types that implement a specific interface, and then specify that interface at runtime. (I know that I need to tag developers using export)

Usage example:

IEnumerable<IExcitingClass> excitingClasses = ClassImporter<IExcitingInterface>.ImportAllFrom(specifyDirectory);

Is it possible?

+3
source share
2 answers

You can create a container using DirectoryCatalog and call container.GetExportedValues<IExcitingClass>. Is this what you want?

+1
source

At run time, you can use the string only to indicate the interface.

    public IEnumerable<object> GetAllInheritors(string interfaceName)
    {
        Assembly assembly = this.GetType().Assembly;
        foreach (var part in Container.Catalog.Parts)
        {
            Type type = assembly.GetType(part.ToString());
            if (type != null)
                if (type.GetInterface(interfaceName) != null)
                {
                    yield return part.CreatePart().GetExportedValue(part.ExportDefinitions.First());
                }
        }
    }
+1
source

Source: https://habr.com/ru/post/1794530/


All Articles