DiManager.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.Linq;
  6. using System.Reflection;
  7. using Microsoft.Extensions.DependencyInjection;
  8. using NLog;
  9. using Quadarax.Foundation.Core.Attributes;
  10. using Quadarax.Foundation.Core.Reflection;
  11. using Quadarax.Foundation.Core.Reflection.Extensions;
  12. using ILogger = NLog.ILogger;
  13. namespace Quadarax.Foundation.Core.Business.Injection
  14. {
  15. /// <summary>
  16. /// Register modules inside defined assemblies. Modules must be flagged by <see cref="DiModuleAttribute"/> and <see cref="DiImplementsOfAttribute"/>
  17. /// </summary>
  18. public static class DiManager
  19. {
  20. #region *** Private fields ***
  21. private static IList<Assembly> _registeredAssemblies = new List<Assembly>();
  22. private static ILogger _logger = LogManager.GetLogger(nameof(DiManager));
  23. #endregion
  24. #region *** Public properties ***
  25. public static string[] RegisteredAssembliesNames =>
  26. _registeredAssemblies.Select(x => x.GetName().ToString()).ToArray();
  27. #endregion
  28. #region *** Public Operations ***
  29. /// <summary>
  30. /// Register all assemblies from current appdomain.
  31. /// </summary>
  32. public static void RegisterAssemblyFromThisAppdomain()
  33. {
  34. RegisterAssemblyFromThisAppdomain(null, null);
  35. }
  36. /// <summary>
  37. /// Register all assemblies from current appdomain by filtering options.
  38. /// </summary>
  39. /// <param name="includedStartsWith"></param>
  40. /// <param name="excludedStartsWith"></param>
  41. public static void RegisterAssemblyFromThisAppdomain([AllowNull]IEnumerable<string> includedStartsWith,[AllowNull] IEnumerable<string> excludedStartsWith)
  42. {
  43. includedStartsWith ??= new List<string>();
  44. excludedStartsWith ??= new List<string>();
  45. foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
  46. {
  47. var isRegister = includedStartsWith.Any() && includedStartsWith.Any(x => assembly.GetName().ToString().StartsWith(x));
  48. isRegister = isRegister && !excludedStartsWith.Any(x => assembly.GetName().ToString().StartsWith(x));
  49. if (isRegister)
  50. RegisterAssembly(assembly);
  51. }
  52. }
  53. /// <summary>
  54. /// Register an assembly to scan and find modules flagged by <see cref="DiModuleAttribute"/>
  55. /// </summary>
  56. /// <param name="assembly"></param>
  57. public static void RegisterAssembly([NotNull]Assembly assembly)
  58. {
  59. if (assembly == null)
  60. throw new ArgumentNullException(nameof(assembly));
  61. if (_registeredAssemblies.Contains(assembly))
  62. return;
  63. _registeredAssemblies.Add(assembly);
  64. var logMessage = $"DiManager register assembly: {assembly.GetName()}";
  65. _logger.Debug(logMessage);
  66. Trace.WriteLine(logMessage,"DI");
  67. }
  68. /// <summary>
  69. /// Scans registered assemblies and register them to <see cref="IServiceCollection"/>
  70. /// </summary>
  71. /// <param name="services">Service definition collection.</param>
  72. public static void ScanAndRegisterDependencyInjections([NotNull]IServiceCollection services)
  73. {
  74. int cntAssemblies = 0;
  75. int cntTypes = 0;
  76. int cntRegistrations = 0;
  77. foreach (var assembly in _registeredAssemblies)
  78. {
  79. cntAssemblies++;
  80. var logMessage = $"Scanning assembly '{assembly.GetName()}' ...";
  81. _logger.Debug(logMessage);
  82. Trace.WriteLine(logMessage,"DI");
  83. var types = assembly.GetTypesWithAttribute<DiModuleAttribute>(true);
  84. foreach (var type in types)
  85. {
  86. cntTypes++;
  87. var attributes = AttributeQuery<DiImplementsOfAttribute>.FindAll(type);
  88. foreach (var attribute in attributes)
  89. {
  90. switch (attribute.LifeCycleType)
  91. {
  92. case LifeCycleTypeEnum.Scoped:
  93. services.AddScoped(attribute.InterfaceTypeImplementing, type);
  94. break;
  95. case LifeCycleTypeEnum.Singleton:
  96. services.AddSingleton(attribute.InterfaceTypeImplementing, type);
  97. break;
  98. case LifeCycleTypeEnum.Transient:
  99. services.AddTransient(attribute.InterfaceTypeImplementing, type);
  100. break;
  101. default:
  102. throw new NotSupportedException($"Not supported registration for LifeCycleType = {attribute.LifeCycleType}");
  103. }
  104. cntRegistrations++;
  105. logMessage = $"DI registered: Type={attribute.InterfaceTypeImplementing.FullName} for Type={type.Name} as LifeCycle={attribute.LifeCycleType}";
  106. _logger.Info(logMessage);
  107. Trace.WriteLine(logMessage,"DI");
  108. }
  109. }
  110. }
  111. var logMessage2 = $"DI registered. Assemblies={cntAssemblies}, Types={cntTypes}, Registrations={cntRegistrations}.";
  112. _logger.Info(logMessage2);
  113. Trace.WriteLine(logMessage2,"DI");
  114. }
  115. #endregion
  116. }
  117. }