NinjectCommandHandler.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using Ninject;
  2. using System;
  3. using System.CommandLine.Binding;
  4. using System.CommandLine.Invocation;
  5. using System.Threading.Tasks;
  6. namespace CustomHostingDemo
  7. {
  8. public interface ICommandHandler<TArg>
  9. {
  10. Task<int> InvokeAsync(InvocationContext context, TArg args);
  11. }
  12. public class NinjectCommandHandler<TArg> : ICommandHandler
  13. {
  14. private readonly IKernel _kernel;
  15. private readonly Type _handlerType;
  16. public NinjectCommandHandler(IKernel kernel, Type handlerType)
  17. {
  18. _kernel = kernel;
  19. _handlerType = handlerType;
  20. if (!typeof(ICommandHandler<TArg>).IsAssignableFrom(_handlerType))
  21. {
  22. throw new ArgumentException($"The handler type must implement ICommandHandler<{typeof(TArg).Name}>", nameof(handlerType));
  23. }
  24. }
  25. public Task<int> InvokeAsync(InvocationContext context)
  26. {
  27. var cmdArgs = _kernel.Get<TArg>();
  28. var binder = new ModelBinder<TArg>();
  29. binder.UpdateInstance(cmdArgs, context.BindingContext);
  30. var handler = (ICommandHandler<TArg>)_kernel.Get(_handlerType);
  31. return handler.InvokeAsync(context, cmdArgs);
  32. }
  33. }
  34. }