autofac笔记
/// <summary> /// 数据源操作接口 /// </summary> public interface IDataSource { /// <summary> /// 获取数据 /// </summary> /// <returns></returns> string GetData(); } public class Oracle : IDataSource { public string GetData() { return "通过Oracle获取数据"; } } class Sqlserver : IDataSource { public string GetData() { return "通过SQLSERVER获取数据"; } } /// <summary> /// 数据源管理类 /// </summary public class DataSourceManager { IDataSource _ds; string Name; /// <summary> /// 根据传入的类型动态创建对象 /// </summary> /// <param name="ds"></param> public DataSourceManager(string name, IDataSource ds) { _ds = ds; Name = name; } public string GetData() { return Name + ":" + _ds.GetData(); } } public static void test3() { var builder = new ContainerBuilder(); builder.RegisterType<DataSourceManager>(); builder.RegisterType<Sqlserver>().Named<IDataSource>("SqlServer"); builder.RegisterType<Oracle>().Named<IDataSource>("Oracel"); using (var container = builder.Build()) { var ds = container.ResolveNamed<IDataSource>("Oracel"); var manager = container.Resolve<DataSourceManager>(new NamedParameter("name", "STONE刘先生"), new NamedParameter("ds", ds)); Console.WriteLine(manager.GetData()); Console.ReadLine(); } }
posted on 2020-02-11 20:42 HOT SUMMER 阅读(124) 评论(0) 编辑 收藏 举报