Ioc容器Autofac介绍

本文详细介绍了Autofac IoC容器的使用方法,包括如何创建容器、注册服务和组件、以及获取实例对象。并通过XML文件进行配置,简化服务和组件的映射过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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类似,也是通过三步完成的。

  1. 创建一个ContainerBuilder,容器构造器。
  2. 登记服务和组件及对应的实例对象
  3. 最后就是通过生成的容器并构造出来的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() ;
        }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值