MEF在运行时替换插件

利用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>(); }

 

替换插件

  1. 先删除后添加
    刷新一下,重新输出。
    public void Recompose()
    {
    directoryCatalog.Refresh();
    container.ComposeParts(directoryCatalog.Parts);
    configs = container.GetExportedValues<IConfig>();
    }

  2. 直接替换
    通过FileWatch监视,一旦有文件变化Unload AppDomain,然后重新加载。

posted on 2018-05-15 22:42  武胜-阿伟  阅读(582)  评论(0编辑  收藏  举报