22 where TClientProxy :
class
24 if (hubConnection ==
null)
25 throw new ArgumentNullException(nameof(hubConnection));
28 throw new ArgumentNullException(nameof(proxy));
30 ProxyOn(hubConnection, typeof(TClientProxy), proxy);
39 static void ProxyOn(
this HubConnection hubConnection, Type proxyType,
object proxyObject)
41 var clientMethods = proxyType.GetMethods();
42 var cancellationTokenType = typeof(CancellationToken);
43 foreach (var clientMethod
in clientMethods)
45 var parametersList = clientMethod
47 .Select(parameterInfo => parameterInfo.ParameterType)
50 var cancellationTokenIndex = parametersList.IndexOf(cancellationTokenType);
51 if (cancellationTokenIndex != -1)
53 parametersList.RemoveAt(cancellationTokenIndex);
55 if (parametersList.IndexOf(cancellationTokenType) != -1)
56 throw new InvalidOperationException(
"Cannot ProxyOn a method with multiple CancellationToken parameters!");
60 var parameters = parametersList.ToArray();
62 object?[] AddCancellationTokenToParametersArray(
object?[] parametersArray)
64 if (cancellationTokenIndex == -1)
65 return parametersArray;
67 var newList = parametersArray.ToList();
68 newList.Insert(cancellationTokenIndex, CancellationToken.None);
69 return newList.ToArray();
72 var returnType = clientMethod.ReturnType;
73 if (returnType != typeof(Task))
75 if (returnType.BaseType != typeof(Task))
76 throw new InvalidOperationException($
"Return type {returnType} of {proxyType.FullName}.{clientMethod.Name} is not supported! Only Task and derivatives are supported.");
78 var resultProperty = returnType.GetProperty(nameof(Task<object>.Result));
82 async (parameterArray, _) =>
84 var task = (Task)clientMethod.Invoke(proxyObject, AddCancellationTokenToParametersArray(parameterArray));
86 return resultProperty.GetValue(task);
96 return (Task)clientMethod.Invoke(proxyObject, AddCancellationTokenToParametersArray(parameterArray));
100 foreach (var inheritedInterface
in proxyType.GetInterfaces())
101 ProxyOn(hubConnection, inheritedInterface, proxyObject);