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类似,也是通过三步完成的。
- 创建一个ContainerBuilder,容器构造器。
- 登记服务和组件及对应的实例对象
- 最后就是通过生成的容器并构造出来的IContainer取对象实例了。
同样的,组件及实例对象的映射关系可以通过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() ;
}