(1) 使用下面的代码,我的容器中正好有 2 个项目,其中包含一个相同的导出插件,我想知道为什么:
(2) 我真的无法实现的其他问题:如何扩展框架以处理不同的插件类型(例如具有不同类型的多个导入,或者将所有插件存储在动态 IEnumerable 左右的一个导入)。我想在我的静态包装类中提供一种通用方法,该方法将发现的插件作为类型和匹配元数据的函数返回。
DirectoryCatalog
导出的插件(驻留在单独的 dll 中,并且在构建时指向其位置。
[Export(typeof(IPlugin))] //<---- If this line is commented out then only one item is imported (why?)
[PluginAttribute(typeof(StrategyPlugin_Test1), "StrategyPlugin", "Plugin1")]
public class StrategyPlugin_Test1 : IPlugin
{
public void DoSomething()
{
Console.WriteLine("I do something");
}
}
以下代码定义了强类型元数据和导入以及执行 MEF 功能的静态类,并且应该包含已发现的插件:
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class PluginAttribute : ExportAttribute
{
public Type PluginType { get; set; }
public string PluginGroupName { get; set; }
public string PluginName { get; set; }
public PluginAttribute(Type pluginType, string pluginGroupName, string pluginName) : base(typeof(IPlugin))
{
PluginType = pluginType;
PluginGroupName = pluginGroupName;
PluginName = pluginName;
}
}
public interface IPluginAttribute
{
Type PluginType { get; }
string PluginGroupName { get; }
string PluginName { get; }
}
public interface IPlugin
{
void DoSomething();
}
public class PluginDefinition
{
[ImportMany(typeof(IPlugin))]
public IEnumerable<Lazy<IPlugin, IPluginAttribute>> Plugins { get; set; }
public PluginDefinition()
{
}
}
这里包含一些核心 MEF 内容的静态类:
public static class PluginManager
{
private static PluginDefinition PluginDefinitions { get; set; }
static PluginManager()
{}
public static void Configure(PluginDefinition pluginDefinitions, IEnumerable<string> pluginDirectories)
{
AggregateCatalog aggregateCatalog = new AggregateCatalog(new DirectoryCatalog(pluginDirectories.FirstOrDefault()));
CompositionContainer container = new CompositionContainer(aggregateCatalog);
container.ComposeParts(pluginDefinitions);
//store plugin definition
PluginDefinitions = pluginDefinitions;
}
public static T GetPlugin<T>(string pluginName, string pluginGroupName) where T : class
{
//how to implement this given type of T could be any of the plugin types ...
//...provided for in an extended PluginDefinition class?
return null;
}
}