這次項目需要用autofac動態注冊插件dll,插件修改或擴展后,在不重新編譯的情況下能加載新的插件。
於是我們用autofac從配置文件注冊。注冊的文件固定named。這樣不管插件怎么變,我們Resolve的地方都是用這個固定的name來獲取插件。
<?xml version="1.0" encoding="utf-8"?> <autofac> <components> <component type="MESClient.Unit.Mes.ICMORpt.ICMORptViewModel,MESClient.Unit.Mes.ICMORpt" service="NFMES.Core.MVVM.IViewModel,NFMES.Core" name="ICMORptViewModel"/> </components> </autofac>
要指定注冊的name,我們在配置中需配置name屬性。
app.config中指定配置文件
<configSections> <section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration"/> </configSections> <autofac configSource="XmlConfig\autofac.config" />
autofac通過配置文件注冊
var builder = new ContainerBuilder(); builder .RegisterModule(new ConfigurationSettingsReader("autofac"));
由於我們的插件dll一般都放在一個插件文件夾下,不在根目錄下,所以autofac注冊會報錯,因為找不到程序集。
我們需要指定程序運行時的掃描目錄
<runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <probing privatePath="MesUnit"/> </assemblyBinding> </runtime>
這樣程序會到跟目錄下的MesUnit文件夾下掃描。
使用插件時,直接Resolve就行了
Container.ResolveNamed<T>("ICMORptViewModel");