IoC组件~Autofac将多实现一次注入,根据别名Resove实例
回到目录
对于IoC容器来说,性能最好的莫过于Autofac了,而对于灵活度来说,它也是值得称赞的,为了考虑系统的性能,我们经常是在系统初始化于将所有依赖注册到容器里,当需要于根据别名把实现拿出来,然后再使用即可;而如果每次使用都是注册-反射,我相信那是很耗性能的,所以我们决定先依赖一次注册,按需反射对象的实例!
通过Named全局注册接口的所有实现
var builder = new ContainerBuilder(); builder.RegisterType<Mul1>() .Named<IMul>("Mul1") .InstancePerDependency(); builder.RegisterType<Mul2>() .Named<IMul>("Mul2") .InstancePerDependency();
通过ResolveNamed反射指定名称的实现
IContainer container = builder.Build(); IMul mul = container.ResolveNamed<IMul>("Mul2");
一般地,我们可以通过数据库或者XML文件来存储实现与接口的对应关系,应用程序在启动时读取这种关系,统一完成注册的过程
注册的方法
var type = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(a => a.GetTypes()) .Where(i => i.Name == "XXX_TaskInfoProvider").FirstOrDefault(); builder.RegisterType(type).Named<ITaskInfoProvider>("XXX_TaskInfoProvider").InstancePerDependency();
可插拔模块-数据实体的设计
/// <summary> /// 可插拔模块 /// </summary> class Module { /// <summary> /// 主键 /// </summary> public int ID { get; set; } /// <summary> /// 目前类型,完整路径 /// </summary> public string ToTypeName { get; set; } /// <summary> /// 接口名称,完整路径 /// </summary> public string FromTypeName { get; set; } /// <summary> /// 描述 /// </summary> public string About { get; set; } }
这样我们在程序的初口就可以统一注入动态的模块了!
一般全局入口可以这样设计
//模块获取 ModuleList = new List<Modules>(); ModuleList.Add(new Modules { ID = 1, FromTypeName = "Progame.IMul", ToTypeName = "Progame.Mul1" }); ModuleList.Add(new Modules { ID = 1, FromTypeName = "Progame.IMul", ToTypeName = "Program.Mul2" }); //统一注册 var builder = new ContainerBuilder(); foreach (var item in ModuleList) { var fromType = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(a => a.GetTypes()) .Where(i => i.FullName == item.FromTypeName).FirstOrDefault(); var toType = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(a => a.GetTypes()) .Where(i => i.FullName == item.ToTypeName).FirstOrDefault(); builder.RegisterType(toType).Named(toType.FullName, fromType).InstancePerDependency(); } container = builder.Build();
这样就通用了...
回到目录
相关推荐
丽丽 2020-06-11
itjavashuai 2020-07-28
smalllove 2020-07-27
willluckysmile 2020-06-29
TiDBPingCAP 2020-06-21
shenxiuwen 2020-06-10
willluckysmile 2020-06-10
MrFuWen 2020-06-09
yuanye0 2020-06-08
whbing 2020-05-19
yuanye0 2020-05-14
kong000dao0 2020-05-10
方志朋 2020-05-08
somyjun 2020-05-01
suixinsuoyu 2020-04-29
咻pur慢 2020-04-22
tianxiaolu 2020-04-06
吾日五省我身 2020-03-28