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();