HelloCommand.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using Microsoft.Extensions.Logging;
  2. using System;
  3. using System.CommandLine;
  4. using System.CommandLine.Invocation;
  5. using System.CommandLine.IO;
  6. using System.CommandLine.Rendering;
  7. using System.Threading.Tasks;
  8. namespace CustomHostingDemo
  9. {
  10. public class HelloCommand : CustomCommand<HelloCommand.HelloArgs>
  11. {
  12. public HelloCommand()
  13. : base("hello", "says hello", typeof(DefaultHandler))
  14. {
  15. AddArgument(new Argument<DateTime>("date", () => DateTime.Today));
  16. AddOption(new Option<bool>("--verbose"));
  17. }
  18. public class HelloArgs
  19. {
  20. public DateTime Date { get; set; }
  21. public bool Verbose { get; set; }
  22. }
  23. public class DefaultHandler : ICommandHandler<HelloArgs>
  24. {
  25. private readonly ILogger _logger;
  26. public DefaultHandler(Logger<DefaultHandler> logger)
  27. {
  28. _logger = logger;
  29. }
  30. public Task<int> InvokeAsync(InvocationContext context, HelloArgs args)
  31. {
  32. context.Console.Out.WriteLine("Hello YOU!");
  33. context.Console.Out.WriteLine($"P: --date {args.Date}");
  34. context.Console.Out.WriteLine($"P: --verbose {args.Verbose}");
  35. _logger.LogInformation("INFO from DefaultHandler");
  36. return Task.FromResult(3);
  37. }
  38. }
  39. }
  40. }