Deserialized The Ramblings of a Web Architect

22Jul/112

Use PostSharp to easily allow MiniProfiler to profile your ASP.NET application

Scott Hanselman has written a great post detailing how to include the MiniProfiler in your ASP.NET application.  I tried the profiler out and it works great.  Its lightweight and easy to configure but by default it does not give you very much information about your requests and method calls.

Admittedly, it is a ”mini” profiler so you cannot expect great things from it, such as memory usage like you would get from a full featured out-of-process profiler – but this thing can go pretty far.

Unfortunately, I did not want to add using() statements all over my code in every method I want to profile.  Being able to mark methods with attributes would be great, and ASP.NET MVC lets you do just that which makes it easy to mark your base controller with an attribute that allows you to profile actions.  This does not, however, give you any information about the methods being called from within the action.

C# has no built in way to intercept method invocation so the only way to accomplish this is to use some sort of Aspect Oriented Programming (AOP) library\utility.  There are a few out there, including:

I’ve decided to use PostSharp Community Edition.  It is a free, commercially backed product, and it works pretty well.  With PostSharp, you can define attributes (or aspects) that allow you to run code before or after a method is invoked and catch & handle exceptions.  IT does this by post-processing the IL that is generated by the C# compiler and modifies the areas of the code necessary to make your code work as you intended.

It does add an additional process to the compilation but if you need this sort of power, its worth it.

Here is the code for using PostSharp and MiniProfiler together

And wherever you want to profile, you can mark either the entire class or a specific methods with [ProfilingAspect] and now you will see those method calls showing up in your MiniProfiler logs.

Pretty easy, isnt it?

Comments (2) Trackbacks (0)
  1. This is exactly what I wanted with an app in production using Postsharp. Thanks for sharing

  2. Wow, hats off for this, as simple as it is… there’s no way I want a bunch of boilerplate code for profiling.

    I was having a hard time justifying find-and-replace on all my DataContext instantiations; might have to see if PostSharp community edition can take care of that too.


Leave a comment

(required)

No trackbacks yet.