MEF import does not work as expected

I have two classes with export:

[Export(typeof(Mod))]
public class CoreMod : Mod
{
    [ImportingConstructor]
    public CoreMod()
    {
      //here goes my constructor
    }
}

[Export(typeof(Mod))]
public class AnotherMod : Mod
{
    [ImportingConstructor]
    public AnotherMod()
    {
      //here goes my constructor
    }
}

      

CoreMod

is in my main assembly, AnotherMod

is in an external assembly. Mod

is in another assembly they referenced.
In my application, I have a class that tries to load Mods via MEF:

class ModManager
{
    [ImportMany(typeof(Mod))]
    public static IEnumerable<Mod> Mods { get; set; }

    public List<Mod> LoadedMods { get; set; } 

    public ModManager()
    {
        AggregateCatalog catalog = new AggregateCatalog();
        catalog.Catalogs.Add(new AssemblyCatalog(typeof(CoreMod).Assembly));
        catalog.Catalogs.Add(new DirectoryCatalog(
            Path.GetDirectoryName(
                new Uri(Assembly.GetExecutingAssembly()
                               .CodeBase).LocalPath)));

        var container = new CompositionContainer(catalog);
        container.ComposeParts(this);

        LoadedMods = Mods.ToList();
    }
}

      

It looks like all imports should be satisfied, but still imports nothing ( Mods

equal to null). What am I doing wrong?

+3


source to share


1 answer


I think what is happening is that you have CompositionContainer

as a function variable, not a class variable. Also, MEF does not support static variable import. Try using this:



class ModManager
{
    [ImportMany(typeof(Mod))]
    public IEnumerable<Mod> Mods { get; set; }

    public List<Mod> LoadedMods { get; set; } 
    CompositionContainer _container;

    public ModManager()
    {
        AggregateCatalog catalog = new AggregateCatalog();
        catalog.Catalogs.Add(new AssemblyCatalog(typeof(CoreMod).Assembly));
        catalog.Catalogs.Add(new DirectoryCatalog(
            Path.GetDirectoryName(
                new Uri(Assembly.GetExecutingAssembly()
                               .CodeBase).LocalPath)));

        _container = new CompositionContainer(catalog);
        this._container.ComposeParts(this);

        this.LoadedMods = this.Mods.ToList();
    }
}

      

+1


source







All Articles