C# autofac的一些使用

这次项目需要用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");