设值注入

namespace Setter
{
    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));
        }
    }
    public class Client
    {
        public ITimeProvider TimeProvider { get; set; }
    }
}

客户端调用实现

  [TestMethod()]
        public void Test()
        {
            Setter.ITimeProvider timeprovider = (new Setter.Assembler()).Creat<Setter.ITimeProvider>();
            Setter.Client cilent = new Setter.Client();
            cilent.TimeProvider = timeprovider;//设置值注入
          

        }

lama用法

  [TestMethod()]
        public void Test()
        {
          
            //改写lama
            var client = new Setter.Client()
            {
                TimeProvider = (new Setter.Assembler()).Creat<Setter.ITimeProvider>()

            };

        }

 

posted on 2013-03-26 21:29  HOT SUMMER  阅读(196)  评论(0编辑  收藏  举报

导航