您的位置:首页 > 其它

Ioc容器Autofac介绍

2012-08-22 15:29 363 查看
Autofac是轻量级的开源Ioc容器,在这里可以下载http://code.google.com/p/autofac/。如果你用过其他的Ioc容器,那么学习Autofac使用也会比较容易,下面将通过一些例子来讲解其用法。

先看一个例子:

首先新建一个工程,添加Autofac引用。





准备代码,和之前的一样

class DataFactory
{

public static IContainer GetContainers()
{
var builder = new ContainerBuilder();

builder.Register<IDal>(c => new OracleDal()).SingleInstance();

return builder.Build() ;
}
}

接下来就是获取对象的实例并调用

<?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() ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: