HelloCommand.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using CustomHostingDemo.Logging;
  2. using Microsoft.Extensions.Configuration;
  3. using System;
  4. using System.CommandLine;
  5. using System.CommandLine.Invocation;
  6. using System.Threading.Tasks;
  7. namespace CustomHostingDemo
  8. {
  9. public class HelloCommand : CustomCommand<HelloCommand.HelloArgs>
  10. {
  11. public HelloCommand()
  12. : base("hello", "says hello", typeof(DefaultHandler))
  13. {
  14. AddArgument(new Argument<DateTime>("date", () => DateTime.Today));
  15. AddOption(new Option<bool>("--verbose"));
  16. }
  17. public class HelloArgs : IDefaultArgs
  18. {
  19. public DateTime Date { get; set; }
  20. public bool Verbose { get; set; }
  21. }
  22. public class DefaultHandler : ICommandHandler<HelloArgs>
  23. {
  24. private readonly ICliLogger _logger;
  25. private readonly IConfiguration _config;
  26. public DefaultHandler(ICliLogger logger, IConfiguration config)
  27. {
  28. _logger = logger;
  29. _config = config;
  30. }
  31. public Task<int> InvokeAsync(InvocationContext context, HelloArgs args)
  32. {
  33. _logger.LogContent($"Hello {_config["Hello"]}! How are you?");
  34. _logger.LogInfo($"P: --date {args.Date}");
  35. _logger.LogInfo($"P: --verbose {args.Verbose}");
  36. return Task.FromResult(0);
  37. }
  38. }
  39. }
  40. }