ServiceCollectionExtensions.cs 1.0 KB

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