public interface ITimeProvider { DateTime CurrentDate { get; } } public class TimeProvider : ITimeProvider { public DateTime CurrentDate { get { return DateTime.Now; } } } //下面实现这个Assembler 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 : IobjectWithTimeProvider //{ // public ITimeProvider TimeProvider { get; set; } //} //通过泛型参数实现接口注入 Client设计 class Client<T> : ITimeProvider where T : ITimeProvider { public T Provider { get; set; } public DateTime CurrentDate { get { return Provider.CurrentDate; } } }
测试
/// <summary> ///这是 ClientTest 的测试类,旨在 ///包含所有 ClientTest 单元测试 ///</summary> [TestClass()] public class ClientTest { [TestMethod()] public void CurrentDateTest() { var client = new Client<ITimeProvider>() { Provider = (new Assembler()).Creat<ITimeProvider>() }; } }