BinderServiceMethodProvider.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. using Grpc.AspNetCore.Server.Model;
  2. using Grpc.Extension.Abstract;
  3. using Microsoft.Extensions.DependencyInjection;
  4. using System;
  5. namespace Grpc.Extension.AspNetCore.Internal
  6. {
  7. internal class BinderServiceMethodProvider<TService> : IServiceMethodProvider<TService> where TService : class
  8. {
  9. public void OnServiceMethodDiscovery(ServiceMethodProviderContext<TService> context)
  10. {
  11. var bindMethodInfo = BindMethodFinder.GetBindMethod(typeof(TService));
  12. // Invoke BindService(ServiceBinderBase, BaseType)
  13. if (bindMethodInfo != null)
  14. {
  15. // The second parameter is always the service base type
  16. var serviceParameter = bindMethodInfo.GetParameters()[1];
  17. var binder = new ProviderServiceBinder<TService>(context, serviceParameter.ParameterType);
  18. try
  19. {
  20. if (typeof(IGrpcService).IsAssignableFrom(typeof(TService)))
  21. bindMethodInfo.Invoke(null, new object[] { binder, typeof(TService) });
  22. else
  23. {
  24. bindMethodInfo.Invoke(null, new object[] { binder, null });
  25. }
  26. }
  27. catch (Exception ex)
  28. {
  29. throw new InvalidOperationException($"Error binding gRPC service '{typeof(TService).Name}'.", ex);
  30. }
  31. }
  32. }
  33. }
  34. }