IOC.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Reflection;
  6. using System.Configuration;
  7. namespace SCC.Common
  8. {
  9. /// <summary>
  10. /// 通过依赖注入方式实现控制反转
  11. /// </summary>
  12. public sealed class IOC
  13. {
  14. /// <summary>
  15. /// //通过接口名称和构造函数的参数得到实现
  16. /// </summary>
  17. /// <typeparam name="T">接口类型</typeparam>
  18. /// <param name="args">构造函数的参数</param>
  19. /// <returns>接口的实现</returns>
  20. public static T Resolve<T>(object[] args = null) where T : class
  21. {
  22. //获取类名
  23. string className = typeof(T).Name.Substring(1);
  24. //通过判断fullName中是否包含`符号来判断是否是泛型
  25. string fullName = typeof(T).FullName;
  26. int flag = fullName.IndexOf('`');
  27. //如果是泛型,需要特殊处理
  28. if (flag != -1)
  29. {
  30. int dot = fullName.LastIndexOf('.', flag);
  31. //这里去掉方法名前面的点和I
  32. className = fullName.Substring(dot + 2);
  33. }
  34. return DependencyInjector.GetClass<T>(className, args);
  35. }
  36. }
  37. /// <summary>
  38. /// 依赖注入
  39. /// </summary>
  40. public sealed class DependencyInjector
  41. {
  42. /// <summary>
  43. /// 根据名称和构造函数的参数加载相应的类
  44. /// </summary>
  45. /// <typeparam name="T">需要加载的类所实现的接口</typeparam>
  46. /// <param name="className">类的名称</param>
  47. /// <param name="args">构造函数的参数(默认为空)</param>
  48. /// <returns>类的接口</returns>
  49. public static T GetClass<T>(string className, object[] args = null) where T : class
  50. {
  51. //获取接口所在的命名空间
  52. string factoryName = typeof(T).Namespace;
  53. //通过依赖注入配置文件获取接口实现所在的命名空间
  54. string dllName = ConfigurationManager.AppSettings[factoryName];
  55. //获取类的全名
  56. string fullClassName = dllName + "." + className + "Services";
  57. //根据dll和类名,利用反射加载类
  58. object classObject = Assembly.Load(dllName).CreateInstance(fullClassName, true, BindingFlags.Default, null, args, null, null);
  59. return classObject as T;
  60. }
  61. }
  62. }