Sometimes when working with C# you discover some hidden gems. Some of them very useful, other ones a little bit harder to find a good way to benefit from their functionality. One of those hidden gems that I discovered some days ago is the DispatchProxy class.
DispatchProxy is a new class in .NET Core that allows you to apply Aspect Oriented Programming techniques using interception.
Let’s try it out by creating a really simple LogInterceptor:
The DispatchProxy class is a little cumbersome and we have to capture our target method using a little dynamic magic(casting would have worked as well):
Now let’s create an interface and a corresponding implementation:
As a final step we create an intercepted version of our class and invoke our method:
Here is our output: