【发布时间】:2011-01-14 15:25:11
【问题描述】:
我正在构建一个实现 MEF 的 Windows 服务。这个想法是服务应该管理子组件并且是可插拔的,其中可以在运行时引入任意数量的新组件,而无需经历完整的服务重新编译和部署场景。组件应该是可插入的,这意味着只要我将输出程序集放到磁盘上的指定文件夹中,Windows 服务就会说“嘿,这里有一个要运行的新组件……”然后就去做。这就是MEF的力量。到目前为止非常酷的东西。
我了解创建 AggregateCatalog 和 CompositionContainer 以导入所有可用子组件(组件)的概念。这一切都很好,并且在最初启动 Windows 服务时可以正常工作。但是,我最终将在运行时引入新组件,因此在某些时候我将需要 CompositionContainer 来识别添加的任何新输出程序集。
我对以下内容的担忧是对性能的任何影响。将 CompositionContainer 逻辑放入如下循环中是否安全/高效:
[ImportMany(AllowRecomposition = true)]
private IEnumerable<Lazy<IMySubComponentTask, IDictionary<string, object>>>
MySubComponentTasks { get; set; }
while (true)
{
//Create a general aggregate catalog
var catalog = new AggregateCatalog();
//Adds all the parts found in the same assembly as the Program class
catalog.Catalogs.Add(new AssemblyCatalog(typeof(MySubComponentTaskFactory).Assembly));
//Create a new directory catalog
var directoryCatalog = new DirectoryCatalog(@".\Extensions");
//Add the DLLs in the directory to the aggregate catalog
catalog.Catalogs.Add(directoryCatalog);
//Create the current composition container to create the parts
var container = new CompositionContainer(catalog);
//Fill the imports of this object
try
{
container.ComposeParts(this);
}
catch (CompositionException compositionException)
{
Console.WriteLine(compositionException.ToString());
}
}
感谢任何反馈或意见。
谢谢, 迈克
【问题讨论】: