Friday, January 3, 2014

Data Access Tracing in .NET (Universal for any provider)

Sometimes I'm surprised to see in .NET some very obvious, required functionality not available. I have to implement it by my own. When you develop database-driven web application you face a lot of issues and you need to diagnose if the issue is in database logic or on middle tier or on client. You can trace client and middle tier easily, but for some reason Microsoft thinks that you don't need the same with database access. Solution they provide to trace SQL requests are supercomplex and heavy (SQL Extended Events,...).

So I had to spend couple of days to research and implement generic DbConnection tracing approach that supposed to work with any DbProvider. This approach should work with direct DbConnection as well as with ORM tools (EntityFramework). The idea is to replace standard DbProviderFactories with a wrappers, that will trace all necessary information. The Idea was taken from Glimpse.Ado.

Here is the code:

And here is what you need to add to web.config:


In application initialization module add line:
TraceableDbProviderFactory.IsEnabled = true;

Enjoy!