这种方式就是在构造函数时候注入类型
直接看例子
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 { ITimeProvider timeProvider; public Client(ITimeProvider timeProvider) { this.timeProvider = timeProvider; } }
那么客户端调用时候
[TestMethod()] public void ClientConstructorTest() { ITimeProvider timeProvider = (new Assembler()).Creat<ITimeProvider>(); Assert.IsNotNull(timeProvider); Client target = new Client(timeProvider); }
这样又一次依赖Assembler达到客户端调用时候无需知道具体类型