serveral IoC Framework has already exist on the market,Take account of compenhensive factor,Autofac is best choice for Ioc, If you want to konw more about competion among the serverals Framework.
you can get the information from web, it will prove that Autofuc is best. Now I will give some simple example how to use Autofac.
the first example:
using Autofac; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IOC { public interface IDataBase { void Select(string sql); } public class Sqlserver : IDataBase { public void Select(string sql) { Console.WriteLine("access sqlserver datebase,T-SQL:"+sql); } } public class Oracle : IDataBase { public void Select(string sql) { Console.WriteLine("access oracle database by,T-SQL: "+sql); } } public class DataBaseManager { IDataBase _database; public DataBaseManager(IDataBase database) { _database = database; } public void Search(string sql) { _database.Select(sql); } } class Program { static void Main(string[] args) { var builder = new ContainerBuilder(); builder.RegisterType<DataBaseManager>(); builder.RegisterType<Sqlserver>().As<IDataBase>(); using (var container = builder.Build()) { var manager = container.Resolve<DataBaseManager>(); manager.Search("SELECT * FROM TB_USER"); } //代码分析; //这里可以通过ContainerBuilder 方法RegsisterType对DataManager进行注册; //当注册的类型在相应得到的容器中可以Resolve你的DatabaseManager实例 //builder.RegisterType<SqlDatabase>().As<IDatabase>();通过AS可以让DatabaseManager类中通过构造函数依赖注入类型相应的接口。 //Build()方法生成一个对应的Container实例,这样,就可以通过Resolve解析到注册的类型实例。 //显然以上的程序中,SqlDatabase或者OracleDatabase已经暴露于客户程序中了,现在我想将该类型选择通过文件配置进行读取。Autofac自带了一个Autofac.Configuration.dll 非常方便地对类型进行配置,避免了程序的重新编译。 Console.ReadLine(); } } }
时间: 2024-12-11 01:28:10