public interface ITimeProvider { DateTime CurrentDate { get; } } public interface IobjectWithTimeProvider { ITimeProvider TimeProvider { get; set; } } 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; } }
[TestClass()] public class ClientTest { [TestMethod] public void Test() { ITimeProvider timeprovider = (new Assembler()).Creat<ITimeProvider>(); IobjectWithTimeProvider objectprovider = new Client(); objectprovider.TimeProvider = timeprovider; } }
与值注入有点类似,客户端去实现这个接口,这样客户端就可以获得类型,然后通过Assembler实现再通过赋值的形式注入