天天看点

属性注入

public interface ITimeProvider
    {
        DateTime CurrentDate { get; }
    }

    public class TimeProvider : ITimeProvider
    {
        public DateTime CurrentDate { get { return DateTime.Now; } }
    }
    public class Assembler
    {
        static Dictionary<Type, Type> dictionary = new Dictionary<Type, Type>();
        static Assembler()
        {
            dictionary.Add(typeof(ITimeProvider), typeof(TimeProvider));
        }

        public object Creat(Type type)
        {
            if ((type == null) || !dictionary.ContainsKey(type))
                throw new NullReferenceException();
            return Activator.CreateInstance(dictionary[type]);
        }

        //泛型方式调用
        public T Creat<T>()
        {
            return (T)Creat(typeof(T));
        }
    }      

自定义特性

[AttributeUsage(AttributeTargets.Class,AllowMultiple=true)]
    sealed class DecoratorAttribute : Attribute
    {
        public readonly object injector;
        readonly Type type;
        public DecoratorAttribute(Type type)
        {
            if (type == null) throw new ArgumentNullException("type");
            this.type = type;
            injector = (new Assembler()).Creat(this.type);
        }
        public Type Type { get { return this.type; } }
    }      

对Assembler再包装

static class AttributeHelper
    {
        public static T Injector<T>(object target) where T:class
        {
            if (target == null) throw new ArgumentNullException("target");
            return (T)(((DecoratorAttribute[])target.GetType().GetCustomAttributes(typeof(DecoratorAttribute), false))
                .Where(x => x.Type == typeof(T))
                .FirstOrDefault()
                .injector);
        }
    }      

实体类

[Decorator(typeof(ITimeProvider))]
    class Client
    {
        public int GetYear()
        {
            var provider = AttributeHelper.Injector<ITimeProvider>(this);
            return provider.CurrentDate.Year;
        }
    }      
/// <summary>
        ///GetYear 的测试
        ///</summary>
        [TestMethod()]
        public void GetYearTest()
        {
            Client target = new Client(); // TODO: 初始化为适当的值
            target.GetType();
        }