C# 12 Interceptors' Purpose

310 views Asked by At

C# 12 will introduce Interceptors, which allow you to intercept a call to a method, but what is the point of that? Why don't I just call the other method in the first place?

And why would I ever want to use one - the syntax doesn't seem to developer friendly? Thank you

2

There are 2 answers

1
AudioBubble On BEST ANSWER

Why would you ever want to use Interceptors?

Well, the thing is, that you aren't supposed to use Interceptors directly, instead they are to be used by, for instance, a source generator, and that explains the handling of them and their akward syntax. They are not intended to be developer-friendly.

What are they even good for then?

A great way to use Interceptors would be for mocking for example.
I see tremendous potential in Interceptors facilitating already simple tasks even more. The reason they were originally implemented though, is because they are an important milestone to the goal of Microsoft of reaching complete AOT support in .Net, because the substitution that Interceptors perform happens purely at compile time. This means, that there is no runtime overhead and no runtime interaction required at all. I believe we will see this feature being used by the .net team to enable features that were exclusive to Reflection and could therefore not be used in AOT-compiled apps in AOT.
Hope that helps..

If you want to learn more about Interceptors, here is the feature specification: Interceptors

0
Marc Gravell On

Why don't I just call the other method in the first place?

To echo @dragon's answer: the typical use-case here is to allow generators that rewrite your code, at build-time, to express the same intent, but in an AOT-compatible way. The example that I lean on here (because I'm biased) is "Dapper": Dapper is a data access library that uses reflection and IL-emit to generate code at runtime that performs things like ADO.NET parameter binding and row parsing. This works, but is 100% incompatible with AOT and trimming. Work is in progress on a generator-based implementation of Dapper that takes your existing Dapper code, but uses interceptors to replace your calls to things like .Query<Customer>(...), using equivalent implementations but which are now AOT and trim friendly - without any changes to your existing code.

the syntax doesn't seem to developer friendly?

It doesn't need to be; it is not expected that anyone will emit interceptors directly or by hand, but always by generators.