ConsoleRunner.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using RackPeek.Domain;
  2. using Spectre.Console;
  3. using Spectre.Console.Cli;
  4. using Spectre.Console.Testing;
  5. namespace Shared.Rcl;
  6. public class ConsoleEmulator : IConsoleEmulator
  7. {
  8. public CommandApp App { get; }
  9. public ConsoleEmulator(IServiceProvider provider)
  10. {
  11. var registrar = new TypeRegistrar(provider);
  12. App = new CommandApp(registrar);
  13. CliBootstrap.BuildApp(App);
  14. }
  15. public async Task<string> Execute(string input)
  16. {
  17. var testConsole = new TestConsole();
  18. testConsole.Width(120);
  19. AnsiConsole.Console = testConsole;
  20. App.Configure(c => c.Settings.Console = testConsole);
  21. await App.RunAsync(input.Split(" ", StringSplitOptions.RemoveEmptyEntries));
  22. return testConsole.Output;
  23. }
  24. }
  25. public sealed class TypeRegistrar : ITypeRegistrar
  26. {
  27. private readonly IServiceProvider _provider;
  28. public TypeRegistrar(IServiceProvider provider)
  29. {
  30. _provider = provider;
  31. }
  32. public void Register(Type service, Type implementation)
  33. {
  34. // DO NOTHING — services must already be registered
  35. }
  36. public void RegisterInstance(Type service, object implementation)
  37. {
  38. // DO NOTHING
  39. }
  40. public void RegisterLazy(Type service, Func<object> factory)
  41. {
  42. // DO NOTHING
  43. }
  44. public ITypeResolver Build()
  45. {
  46. return new TypeResolver(_provider);
  47. }
  48. }
  49. public sealed class TypeResolver : ITypeResolver
  50. {
  51. private readonly IServiceProvider _provider;
  52. public TypeResolver(IServiceProvider provider)
  53. {
  54. _provider = provider;
  55. }
  56. public object? Resolve(Type? type)
  57. => type == null ? null : _provider.GetService(type);
  58. }