csharp / expert
Snippet
Dynamic Interception with DispatchProxy
DispatchProxy is a high-performance mechanism for implementing the Decorator pattern dynamically. Unlike heavy mocking frameworks, it is part of the standard library and allows you to intercept calls to interface methods at runtime. This is ideal for cross-cutting concerns like logging, profiling, or implementing test doubles without manually writing wrapper classes for every interface.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System.Reflection;public interface IService { void DoWork(); }public class ServiceProxy : DispatchProxy{private object? _target;protected override object? Invoke(MethodInfo? targetMethod, object?[]? args){Console.WriteLine($"Before calling {targetMethod?.Name}");var result = targetMethod?.Invoke(_target, args);Console.WriteLine($"After calling {targetMethod?.Name}");return result;}public static T Create<T>(T target) where T : class{object proxy = Create<T, ServiceProxy>();((ServiceProxy)proxy)._target = target;return (T)proxy;}}
Breakdown
1
protected override object? Invoke(MethodInfo? targetMethod, object?[]? args)
The central point where all method calls on the proxy instance are diverted for processing.
2
Create<T, ServiceProxy>()
A static factory method that generates a runtime type implementing T and inheriting from ServiceProxy.