Search code examples
asp.netmef

Problem with MEF


I have the folllowing:

private void ConfigureMEFContainer()
    {
        _catalog = new DirectoryCatalog(_pluginsPath);
        _container = new CompositionContainer(_catalog);
    }

       private readonly string _pluginsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins");
    private DirectoryCatalog _catalog;
    private CompositionContainer _container;

Container is passed to another class:

        var batch = new CompositionBatch();
        batch.AddPart(this);

        container.Compose(batch);

        [ImportMany(typeof(IOnAnnotationCreatedPlugin))]
    public Lazy<IOnAnnotationCreatedPlugin, IAnnotationPluginMetadata>[] OnCreatedPlugins { get; set; }

    [ImportMany(typeof(IOnAnnotationCreatingPlugin))]
    public Lazy<IOnAnnotationCreatingPlugin, IAnnotationPluginMetadata>[] OnCreatingPlugins { get; set; }

    [ImportMany(typeof(IOnAnnotationUpdatedPlugin))]
    public Lazy<IOnAnnotationUpdatedPlugin, IAnnotationPluginMetadata>[] OnUpdatedPlugins { get; set; }

    [ImportMany(typeof(IOnAnnotationUpdatingPlugin))]
    public Lazy<IOnAnnotationUpdatingPlugin, IAnnotationPluginMetadata>[] OnUpdatingPlugins { get; set; }

All the collections above are empty!

Any help?


Solution

  • Thanks for your responses. I changed the code to the following and now it works fine. I believe, I had a problem with the custom Export Attribute and the Metadata interface. Here is the complete code in case someone else had the same problem:

    public interface IAnnotationServicePluginMetadata
    {
        string Name { get; }
    
        [DefaultValue(0)]
        int Priority { get; }
    }
    
    [MetadataAttribute]  
    [AttributeUsage(AttributeTargets.Class, AllowMultiple=false)]  
    public class AnnotationServicePluginMetadataAttribute : ExportAttribute  
    {
       public AnnotationServicePluginMetadataAttribute()
           : base(typeof(IAnnotationServicePluginMetadata))
       {
       }  
    
       public string Name { get; set; }
       public int Priority { get; set; }
    } 
    

    Using the above:

    [Export(typeof(IOnAnnotationUpdatedPlugin))]
    [AnnotationServicePluginMetadata(Name = "OnUpdatedPlugin", Priority = 1)]
    public class OnUpdatedPlugin : IOnAnnotationUpdatedPlugin
    { }
    

    Properties as follows:

        [ImportMany(typeof(IOnAnnotationUpdatedPlugin))]
        public IEnumerable<Lazy<IOnAnnotationUpdatedPlugin, IAnnotationServicePluginMetadata>> OnUpdatedPlugins { get; set; }
    

    Hope that helps. Regards