{C#} MEF如何在运行时替换插件
2016-10-27 本文已影响0人
windflow
主要是利用AppDomain的ShadowCopy特性。
var setup = new AppDomainSetup
{
CachePath = cachePath,
ShadowCopyFiles = "true",
ShadowCopyDirectories = pluginPath
};
之后创建程序集
domain = AppDomain.CreateDomain("Host_AppDomain", AppDomain.CurrentDomain.Evidence, setup);
var asmfullname = typeof(UseConfig).Assembly.FullName;
var typefullname = typeof(UseConfig).FullName;
useConfig = (UseConfig)domain.CreateInstanceAndUnwrap(asmfullname, typefullname);
useConfig.Build();
在创建好的程序集里通过MEF加载插件
useConfig.cs:
public void Build()
{
var regBuilder = new RegistrationBuilder();
regBuilder.ForTypesDerivedFrom<IConfig>().Export<IConfig>();
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(typeof(UseConfig).Assembly, regBuilder));
directoryCatalog = new DirectoryCatalog(pluginPath, regBuilder);
catalog.Catalogs.Add(directoryCatalog);
container = new CompositionContainer(catalog);
container.ComposeExportedValue(container);
configs = container.GetExportedValues<IConfig>();
}
替换插件有两种情况
-
先删除后添加
刷新一下,重新输出。
public void Recompose()
{
directoryCatalog.Refresh();
container.ComposeParts(directoryCatalog.Parts);
configs = container.GetExportedValues<IConfig>();
} -
直接替换
通过FileWatch监视,一旦有文件变化Unload AppDomain,然后重新加载。