小結:c#Constructor建構函式注入
阿新 • • 發佈:2019-01-22
1、建立介面
public interface ITimeProvider
{
DateTime CurrentDate { get; }
string CurrentYear { get; }
}
2、繼承介面,實現類
public class TimeProvider : ITimeProvider { public DateTime CurrentDate { get { return DateTime.Now; } } public string CurrentYear { get { return DateTime.Now.Year.ToString(); } } }
3、建立注入機制
public class Assembler { private static Dictionary<Type, Type> dictionary = new Dictionary<Type, Type>(); public Assembler() { dictionary.Add(typeof(ITimeProvider), typeof(TimeProvider)); } public object Create(Type type) { if (type == null || !dictionary.ContainsKey(type)) throw new NullReferenceException(); Type targetType = dictionary[type]; return Activator.CreateInstance(targetType); } public T Create<T>() { return (T)Create(typeof(T)); } }
4、客戶端呼叫
public class Client { private ITimeProvider timeProvider; public Client(ITimeProvider timeProvider) { this.timeProvider = timeProvider; } public string GetYear() { return timeProvider.CurrentYear .ToString(); } public string GetDatetime() { return timeProvider.CurrentDate.ToString(); } }
5、使用實現
ITimeProvider timeProvider = (new Assembler()).Create<ITimeProvider>();
Client clinet = new Client(timeProvider);
Console.WriteLine(clinet.GetYear());
Console.WriteLine(clinet.GetDatetime());