Ioc容器Autofac介绍
Autofac是輕量級的開源Ioc容器,在這里可以下載http://code.google.com/p/autofac/。如果你用過其他的Ioc容器,那么學習Autofac使用也會比較容易,下面將通過一些例子來講解其用法。
先看一個例子:
首先新建一個工程,添加Autofac引用。
?
準備代碼,和之前的一樣
interface IDal { void save(); } class SqlServerDal : IDal { public void save() { Console.WriteLine("SqlServer save."); } } class OracleDal : IDal { public void save() { Console.WriteLine("Oracle save."); } }
接下來就是Ioc的實現了:
class DataFactory { public static IContainer GetContainers() { var builder = new ContainerBuilder(); builder.Register<IDal>(c => new OracleDal()).SingleInstance(); return builder.Build() ; } }
接下來就是獲取對象的實例并調用
static void Main(string[] args) { var container = DataFactory.GetContainers(); container.Resolve<IDal>().save(); Console.Read(); }
好,我們來分析一下代碼,看看Autofac容器的構造及獲取實例的過程:從代碼中可以看出,和Unity類似,也是通過三步完成的。
?
同樣的,組件及實例對象的映射關系可以通過XML文件進行配置:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration"/> </configSections> <autofac> <components> <component type="AutofacDemo.OracleDal, AutofacDemo" service="AutofacDemo.IDal, AutofacDemo" /> </components> </autofac> </configuration>
調用配置文件注冊組件
public static IContainer GetContainers() { var builder = new ContainerBuilder(); // builder.Register<IDal>(c => new OracleDal()).SingleInstance(); builder.RegisterModule(new ConfigurationSettingsReader("autofac")); return builder.Build() ; }
轉載于:https://www.cnblogs.com/zgqys1980/archive/2012/08/22/2650921.html
總結
以上是生活随笔為你收集整理的Ioc容器Autofac介绍的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [LeetCode] 搜索旋转排序数组
- 下一篇: Comet OJ - Contest #