IOCContainer.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System.Collections.Generic;
  2. using System;
  3. namespace Blue
  4. {
  5. /// <summary>
  6. /// IOC容器---根据类型存储Object
  7. /// </summary>
  8. public class IOCContainer
  9. {
  10. private Dictionary<Type, object> container = new Dictionary<Type, object>();
  11. /// <summary>
  12. /// 将实例注入IOC容器
  13. /// </summary>
  14. public void Register<T>() where T:new()
  15. {
  16. Register(new T());
  17. }
  18. /// <summary>
  19. /// 将实例注入IOC容器
  20. /// </summary>
  21. public void Register<T>(T instance)
  22. {
  23. Type t = typeof(T);
  24. if (container.ContainsKey(t))
  25. {
  26. container[t] = instance;
  27. }
  28. else
  29. {
  30. container.Add(t,instance);
  31. }
  32. }
  33. /// <summary>
  34. /// 根据类型从IOC容器获取对象
  35. /// </summary>
  36. public object Get(Type type)
  37. {
  38. if (container.TryGetValue(type,out object instance))
  39. {
  40. return instance;
  41. }
  42. return default;
  43. }
  44. /// <summary>
  45. /// 从IOC容器获取指定的实例
  46. /// </summary>
  47. public T Get<T>()
  48. {
  49. Type t = typeof(T);
  50. if (container.TryGetValue(t, out object instance))
  51. {
  52. return (T)instance;
  53. }
  54. else
  55. {
  56. throw new Exception("Can Not Find Instance of type "+t.FullName+",Please Call Register At First!");
  57. }
  58. }
  59. }
  60. }