DotNet · 2022年3月22日

MEF中延迟加载使用自定义元素方法示例1(推荐)

定义实现接口的Attribute类,必须要标记[MetadataAttribute]元素性 
 public interface IPluginID
    {
        string Name { get; }
    }


    [MetadataAttribute]
    [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
    public class PluginIDAttribute : Attribute, IPluginID
    {
        public string Name { get; private set; }


        public PluginIDAttribute(string pName)
        {
            this.Name = pName;
        }
    }

在使用时,根据元标记来区分使用
[ImportMany]
    public Lazy<IPluginDemo, IPluginID>[] plugins;

        ToolStripMenuItem item = new ToolStripMenuItem("插件");
            ms.Items.Add(item);    
            foreach (var plugin in plugins)
            {
                ToolStripMenuItem subItem = new ToolStripMenuItem(plugin.Metadata.Name);                    //可以根据无标记名称生成菜单
                subItem.Click += (s, arg) => { plugin.Value.Do(); };
                item.DropDownItems.Add(subItem);
            }

最新电影,电视剧,尽在午夜剧场

电影电视剧午夜不寂寞