码迷,mamicode.com
首页 > 其他好文 > 详细

IOC容器特性注入第五篇:查找(Attribute)特性注入

时间:2014-06-12 18:25:17      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   http   

前面几篇文章分别介绍:程序集反射查找,特性,容器,但它们之间贯穿起来,形成查找Attribute注入IOC容器,就得需要下面这个类帮忙:

1.DependencyAttributeRegistrator(依赖特性注入类),有它才能在引擎初始化的时候 查找Attribute 进行注入

bubuko.com,布布扣
    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
    }
bubuko.com,布布扣

大家可以很清楚看到了吧。其实很简单! 

IOC容器特性注入第五篇:查找(Attribute)特性注入,布布扣,bubuko.com

IOC容器特性注入第五篇:查找(Attribute)特性注入

标签:style   class   blog   code   java   http   

原文地址:http://www.cnblogs.com/flyfish2012/p/3781764.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!