This repository has been archived by the owner on Jun 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
DynamicTargetBehavior.cs
111 lines (98 loc) · 4.95 KB
/
DynamicTargetBehavior.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Avatars;
using Microsoft.CSharp.RuntimeBinder;
namespace Samples.TargetInvocation
{
public class DynamicTargetBehavior : IAvatarBehavior
{
readonly ConcurrentDictionary<MethodBase, Func<IMethodInvocation, IMethodReturn>> invokers = new();
readonly HashSet<MethodBase> unsupported = new();
readonly object target;
public DynamicTargetBehavior(dynamic target) => this.target = target;
public bool AppliesTo(IMethodInvocation invocation)
=> !unsupported.Contains(invocation.MethodBase) &&
// NOTE: doing the proper binding for ref/out arguments is quite complicated
// with the dynamic approach, since we would need to generate variables to keep the
// out/ref before/after the call. The generated IL from a dynamic call for that
// scenario is significantly more complicated than for "normal" method calls.
!invocation.MethodBase.GetParameters().Any(p => p.IsOut || p.ParameterType.IsByRef);
public IMethodReturn Execute(IMethodInvocation invocation, ExecuteHandler next)
{
var invoker = invokers.GetOrAdd(invocation.MethodBase, method => GetInvoker(method));
try
{
return invoker(invocation);
}
catch (RuntimeBinderException)
{
unsupported.Add(invocation.MethodBase);
return next.Invoke(invocation, next);
}
}
Func<IMethodInvocation, IMethodReturn> GetInvoker(MethodBase method)
{
var parameters = method.GetParameters();
var binder = Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(
(method is MethodInfo mi && mi.ReturnType == typeof(void)) ? CSharpBinderFlags.ResultDiscarded : CSharpBinderFlags.None,
method.Name,
method.IsGenericMethod ? method.GetGenericArguments() : Array.Empty<Type>(),
GetType(),
new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) }.Concat(
method.GetParameters().Select(p => CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, p.Name))));
if (method is MethodInfo info && info.ReturnType == typeof(void))
{
var delegateType = Type.GetType("System.Action`" + (parameters.Length + 2), true)!
.MakeGenericType(
new[] { typeof(CallSite), typeof(object) }
.Concat(parameters.Select(p => p.ParameterType))
.ToArray());
var site = typeof(CallSite<>).MakeGenericType(delegateType)
.InvokeMember("Create", BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod, null, null, new[] { binder });
var target = (Delegate)site?.GetType().GetField("Target")?.GetValue(site)!;
return invocation =>
{
var args = invocation.Arguments.Select(x => x.RawValue).ToArray();
try
{
target.DynamicInvoke(new[] { site, this.target }.Concat(args).ToArray());
return invocation.CreateReturn();
}
catch (TargetInvocationException tie)
{
return invocation.CreateExceptionReturn(tie.InnerException!);
}
};
}
else
{
var delegateType = Type.GetType("System.Func`" + (parameters.Length + 3), true)!
.MakeGenericType(
new[] { typeof(CallSite), typeof(object) }
.Concat(parameters.Select(p => p.ParameterType))
.Concat(new[] { typeof(object) })
.ToArray());
var site = typeof(CallSite<>).MakeGenericType(delegateType)
.InvokeMember("Create", BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod, null, null, new[] { binder });
var target = (Delegate)site?.GetType().GetField("Target")?.GetValue(site)!;
return invocation =>
{
var args = invocation.Arguments.Select(x => x.RawValue).ToArray();
try
{
var result = target.DynamicInvoke(new[] { site, this.target }.Concat(args).ToArray());
return invocation.CreateValueReturn(result);
}
catch (TargetInvocationException tie)
{
return invocation.CreateExceptionReturn(tie.InnerException!);
}
};
}
}
}
}