using System.Collections.Generic; using System; namespace Blue { /// /// IOC容器---根据类型存储Object /// public class IOCContainer { private Dictionary container = new Dictionary(); /// /// 将实例注入IOC容器 /// public void Register() where T:new() { Register(new T()); } /// /// 将实例注入IOC容器 /// public void Register(T instance) { Type t = typeof(T); if (container.ContainsKey(t)) { container[t] = instance; } else { container.Add(t,instance); } } /// /// 根据类型从IOC容器获取对象 /// public object Get(Type type) { if (container.TryGetValue(type,out object instance)) { return instance; } return default; } /// /// 从IOC容器获取指定的实例 /// public T Get() { Type t = typeof(T); if (container.TryGetValue(t, out object instance)) { return (T)instance; } else { throw new Exception("Can Not Find Instance of type "+t.FullName+",Please Call Register At First!"); } } } }