ServiceCollectionExtensions.cs 1013 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using System.Reflection;
  2. using Microsoft.Extensions.DependencyInjection;
  3. using Spectre.Console.Cli;
  4. namespace Shared.Rcl;
  5. public static class ServiceCollectionExtensions
  6. {
  7. public static IServiceCollection AddCommands(
  8. this IServiceCollection services)
  9. {
  10. var commandTypes = Assembly.GetAssembly(typeof(ServiceCollectionExtensions))
  11. ?.GetTypes()
  12. .Where(t =>
  13. t is { IsAbstract: false, IsInterface: false } &&
  14. IsAsyncCommand(t)
  15. );
  16. foreach (var type in commandTypes) services.AddScoped(type);
  17. return services;
  18. }
  19. private static bool IsAsyncCommand(Type type)
  20. {
  21. while (type != null)
  22. {
  23. if (type.IsGenericType &&
  24. type.GetGenericTypeDefinition() == typeof(AsyncCommand<>))
  25. return true;
  26. if (type == typeof(AsyncCommand))
  27. return true;
  28. type = type.BaseType!;
  29. }
  30. return false;
  31. }
  32. }