对于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();
这样就通用了...