Search code examples
c#c#-4.0mef

Multiple Properties and Methods using MEF


I am trying to implment a plugin framework using MEF and I have an interface

public interface IPlugin
{
   string SomeProperty {get;set;}
   IList<string> DoSomething(string somevalue);
}

I was thinking of doing an implementation which does Import Many

public class MainContainer : IPlugin
{
    public string _name;

    public MainContianer(){

    }
    public MainContainer(string name){
       _name = name;
    }

    [ImportMany]
    List<Lazy<IPlugin, string>> plugins;

    string SomeProperty { get { 
       var plugin  = plugins.Where(a => a.Metadata.Equals(_name)).FirstOrDefault();
            if (plugin  != null) {
                return plugin.Value.SomeProperty;
            }
            throw new CustomException();
    } }

    List<string> DoSomething(string value){
        var plugin  = plugins.Where(a => a.Metadata.Equals(_name)).FirstOrDefault();
            if (plugin  != null) {
                return plugin.Value.DoSomething(value);
            }
            throw new CustomException();
    }
}

My Question is that Is there a better way to the implement this rather then me writing the same block for each property and method.

var plugin  = plugins.Where(a => a.Metadata.Equals(_name)).FirstOrDefault();
if (plugin  != null) {
   return plugin.Value.xxx
}

Solution

  • I was looking at all wrong. I have updated my code, the Calculator Example pushed me in the wrong direction.

    public class MainContainer
    {
        private CompositionContainer _container;
    
        [ImportMany]
        public IEnumerable<IPlugin> Plugins;
    
        public AdapterProvider(string pluginpath)
        {
            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new DirectoryCatalog(pluginpath));
            _container = new CompositionContainer(catalog);
            _container.ComposeParts(this);
        }
    }
    

    is enough,

    Moderators can close this as an invalid question.