Yesterday I blogged about the usage of DiagnosticSource to capture database specific events. The code we ended up with looked like this:
What is rather unfortunate is that you are working with generic events and that you need to use magic strings and reflection to capture the object data:
A solution exists through the usage of the Microsoft.Extensions.DiagnosticAdapter package. This Nuget package will use code generation to avoid the cost of reflection.
- Add a reference to the Microsoft.Extensions.DiagnosticAdapter package:
dotnet add package Microsoft.Extensions.DiagnosticAdapter
- Update the implementation to use the SubscribeWithAdapter extension method:
- Now we no longer need to implement the
IObserver<KeyValuePair<string, object>>
interface. Instead, for each event that we want to handle, we need to declare a separate method, marking it with an attributeDiagnosticNameAttribute.
The parameters of these methods are the parameters of the event being processed: