标签:
使用autofac 实现依赖注入
1.引用 autofac.dll 和 autofac.configuration.dll
2.新增接口 IDAL
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AutoFacTest { public interface IDAL { void select(string msg); } }
2.新增 SqlserverDAL 类和 OracleDAL类,并继承IDAL
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AutoFacTest { public class SqlServerDAL:IDAL { public void select(string msg) { Console.WriteLine("this is sqlserver:"+msg); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AutoFacTest { public class OracleDAL:IDAL { public void select(string msg) { Console.WriteLine("this is Oracle:" + msg); } } }
3. 在程序里直接实现IOC注入
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Autofac; namespace AutoFacTest { class Program { static void Main(string[] args) { // //直接指定实例类型 var builder = new ContainerBuilder(); builder.RegisterType<IDAL>(); builder.RegisterType<OracleDAL>().As<IDAL>(); using (var container = builder.Build()) { var manager=container.Resolve<IDAL>(); manager.select("小xiaoniao"); } Console.ReadLine(); } } }
4.也可以通过引用Autofac.Configuration.dll 来配置 App.config或Web.config 配置文件注入
如下:
<configuration> <configSections> <section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration"/> </configSections> <autofac defaultAssembly="AutoFacTest"> <components> <component type="AutoFacTest.OracleDAL, AutoFacTest" service="AutoFacTest.IDAL" /> </components> </autofac>
直接注入显示结果:this is Oracle:小xiaoniao
将 builder.RegisterType<OracleDAL>().As<IDAL>(); 改成 builder.RegisterType<SqlserverDAL>().As<IDAL>(); 则会显示:this is sqlserver:小xiaoniao
直接注入和配置文件注入显示:
this is Oracle:直接注入,小xiaoniao
this is Oracle:配置文件注入,小xiaoniao
标签:
原文地址:http://www.cnblogs.com/tiancai/p/4695735.html