NinjectCommandHandler.cs 1.3 KB

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