首页 > 代码库 > IOC容器特性注入第五篇:查找(Attribute)特性注入
IOC容器特性注入第五篇:查找(Attribute)特性注入
前面几篇文章分别介绍:程序集反射查找,特性,容器,但它们之间贯穿起来,形成查找Attribute注入IOC容器,就得需要下面这个类帮忙:
1.DependencyAttributeRegistrator(依赖特性注入类),有它才能在引擎初始化的时候 查找Attribute 进行注入
public class DependencyAttributeRegistrator { #region Fields private readonly ITypeFinder _finder; private readonly IContainerManger _containerManger; #endregion #region .ctor public DependencyAttributeRegistrator(ITypeFinder finder, IContainerManger containerManger) { this._finder = finder; this._containerManger = containerManger; } #endregion #region Methods public virtual IEnumerable<AttributeInfo<DependencyAttribute>> FindServices() { foreach (Type type in _finder.FindClassesOfType<object>()) { var attributes = type.GetCustomAttributes(typeof (DependencyAttribute), false); //这句是关键 查找所有特性 foreach (DependencyAttribute attribute in attributes) { yield return new AttributeInfo<DependencyAttribute> { Attribute = attribute, DecorateType = type }; } } } public virtual void RegisterServices() { this.RegisterServices(this.FindServices()); } public virtual void RegisterServices(IEnumerable<AttributeInfo<DependencyAttribute>> services) { services = services.OrderBy(it => it.Attribute.Order); foreach (var info in services) { Type serviceType = info.Attribute.ServiceType ?? info.DecorateType; _containerManger.AddComponent(serviceType,info.DecorateType,info.Attribute.Key,info.Attribute.LiftStyle); } } public virtual IEnumerable<AttributeInfo<DependencyAttribute>> FilterServices( IEnumerable<AttributeInfo<DependencyAttribute>> services, params string[] configurationKeys) { return services.Where(s => s.Attribute.Configuration == null || configurationKeys.Contains(s.Attribute.Configuration)); } #endregion }
大家可以很清楚看到了吧。其实很简单!
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。