Friday, March 23, 2018

Impress your colleagues with your knowledge about... the DispatchProxy class.

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:


1 comment:

Bernie Seabrook said...

I think I just found my favorite tech blog ever. Thanks. Feel free to delete this comment. I couldn't find another way to thank you.