IoC~高效的Autofac
毫无疑问,微软最青睐的IoC容器不是spring.net,unity而是Autofac,因为他的高效,因为他的简洁,所以就边微软主导的orchard项目用的也是它,下面我用一个简单
的实例来说明一个Autofac的用法。
1 /// <summary> 2 /// DB Operate Interface 3 /// </summary> 4 public interface IRepository 5 { 6 void Get(); 7 } 8 /// <summary> 9 /// 对SQL数据源操作10 /// </summary>11 public class SqlRepository : IRepository12 {13 #region IRepository 成员14 15 public void Get()16 {17 Console.WriteLine("sql数据源");18 }19 20 #endregion21 }22 /// <summary>23 /// 对redis数据源操作24 /// </summary>25 public class RedisRepository : IRepository26 {27 #region IRepository 成员28 29 public void Get()30 {31 Console.WriteLine("Redis数据源");32 }33 34 #endregion35 }36 /// <summary>37 /// 数据源基类38 /// </summary>39 public class DBBase40 {41 public DBBase(IRepository iRepository)42 {43 _iRepository = iRepository;44 }45 public IRepository _iRepository;46 public void Search(string commandText)47 {48 _iRepository.Get();49 }50 }
我们现在去调用它一样吧:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 //直接指定实例类型 6 var builder = new ContainerBuilder(); 7 builder.RegisterType<DBBase>(); 8 builder.RegisterType<SqlRepository>().As<IRepository>(); 9 using (var container = builder.Build())10 {11 var manager = container.Resolve<DBBase>();12 manager.Search("SELECT * FORM USER");13 }14 15 //通过配置文件实现对象的创建16 var builder2 = new ContainerBuilder();17 builder2.RegisterType<DBBase>();18 builder2.RegisterModule(new ConfigurationSettingsReader("autofac"));19 using (var container = builder2.Build())20 {21 var manager = container.Resolve<DBBase>();22 manager.Search("SELECT * FORM USER");23 }24 //通过配置文件,配合Register方法来创建对象25 var builder3 = new ContainerBuilder();26 builder3.RegisterModule(new ConfigurationSettingsReader("autofac"));27 builder3.Register(c => new DBBase(c.Resolve<IRepository>()));28 using (var container = builder3.Build())29 {30 var manager = container.Resolve<DBBase>();31 manager.Search("SELECT * FORM USER");32 }33 34 Console.ReadKey();35 }36 }
怎么样,搞简单吧,下一讲我将针对orchard项目,说说Autofac在具体项目中的使用。
TAG: