IOC容器特性注入第三篇:Attribute封装

Attribute(特性)=>就是对类,方法,字段的自定义属性的基类。可以利用Attribute对类,方法等进行自定义描述,方便区分。

既然如此,那我们就可以那些需要注入IOC容器和不需要注入IOC容器的服务类就可以一目了然的区分出来,从而确保系统初始化的时候,注入容器的不影响性能。

这里主要有2个封装类:特性描述类(AttributeInfo)和依赖特性类(DependencyAttribute)

 1.AttributeInfo<T>

    public class AttributeInfo<T> {

        /// <summary>
        /// 一个属性检索类型描述符
        /// </summary>
        public T Attribute { get; set; }

        /// <summary>
        /// 特定类型特性描述
        /// </summary>
        public Type DecorateType { get; set; }
    }

2.DependencyAttribute

    [AttributeUsage(AttributeTargets.Class,AllowMultiple = true)]
    public class DependencyAttribute:Attribute {
        public DependencyAttribute(ComponentLifeStyle lifeStyle = ComponentLifeStyle.Transient)
        {
            this.LiftStyle = lifeStyle;
        }

        public DependencyAttribute(Type serviceType, ComponentLifeStyle lifeStyle = ComponentLifeStyle.Transient)
        {
            this.ServiceType = serviceType;
            this.LiftStyle = lifeStyle;
        }
        #region Properties
        /// <summary>
        /// 服务类型
        /// </summary>
        public  Type ServiceType { get; protected set; }
        /// <summary>
        /// 生命周期
        /// </summary>
        public ComponentLifeStyle LiftStyle { get; protected set; }
        /// <summary>
        /// 关键字
        /// </summary>
        public  string Key { get; set; }
        /// <summary>
        /// 配置
        /// </summary>
        public  string Configuration { get; set; }
        /// <summary>
        /// 排序
        /// </summary>
        public  int Order { get; set; }
        #endregion
    }

  其中:AttributeInfo<T> 中的T 其实就是DependencyAttribute的约束,利用这个查找所有加了DependencyAttribute的服务类

下一篇:

IOC容器特性注入第四篇:容器初始化

原文地址:https://www.cnblogs.com/flyfish2012/p/3780399.html