IOC.cs 2.3 KB

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