-
Notifications
You must be signed in to change notification settings - Fork 7
/
HubInterceptor.cs
79 lines (70 loc) · 2.88 KB
/
HubInterceptor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System.ComponentModel;
using System.Reflection;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using System.Xml.XPath;
using Castle.DynamicProxy;
using Microsoft.AspNetCore.SignalR.Client;
namespace SignalR.Strong.Dynamic
{
internal class HubInterceptor : IAsyncInterceptor
{
private readonly HubConnection _conn;
public HubInterceptor(HubConnection connection)
{
_conn = connection;
}
public void InterceptSynchronous(IInvocation invocation)
{
invocation.ReturnValue = _conn.SendCoreAsync(invocation.Method.Name, invocation.Arguments);
}
public void InterceptAsynchronous(IInvocation invocation)
{
invocation.ReturnValue = InternalInterceptAsynchronous(invocation);
}
public void InterceptAsynchronous<TResult>(IInvocation invocation)
{
invocation.ReturnValue = InternalInterceptAsynchronous<TResult>(invocation);
}
private async Task InternalInterceptAsynchronous(IInvocation invocation)
{
if (hasChannelReaderArgument(invocation.Method))
{
var (args, token) = HubInteractionHelpers.ParseIntoArgsAndToken(invocation.Arguments);
await _conn.SendCoreAsync(invocation.Method.Name, args, token);
}
else
{
await _conn.InvokeCoreAsync(invocation.Method.Name, invocation.Arguments);
}
}
private bool hasChannelReaderArgument(MethodInfo method)
{
foreach (var parameter in method.GetParameters())
{
if (typeof(ChannelReader<>).IsAssignableFrom(parameter.ParameterType.GetGenericTypeDefinition()))
{
return true;
}
}
return false;
}
private async Task<TResult> InternalInterceptAsynchronous<TResult>(IInvocation invocation)
{
Task<TResult> ret = null;
if (typeof(TResult).IsConstructedGenericType && typeof(TResult).GetGenericTypeDefinition() == typeof(ChannelReader<>))
{
var (args, token) = HubInteractionHelpers.ParseIntoArgsAndToken(invocation.Arguments);
var method = typeof(Microsoft.AspNetCore.SignalR.Client.HubConnectionExtensions).GetMethod("StreamAsChannelCoreAsync")
.MakeGenericMethod(typeof(TResult).GenericTypeArguments[0]);
ret = (Task<TResult>) method.Invoke(null, new object[] {_conn, invocation.Method.Name, args, token});
}
else
{
ret = _conn.InvokeCoreAsync<TResult>(invocation.Method.Name, invocation.Arguments);
}
return await ret;
}
}
}