Skip to content

Instantly share code, notes, and snippets.

@nootn
Created July 9, 2012 13:10
Show Gist options
  • Save nootn/3076470 to your computer and use it in GitHub Desktop.
Save nootn/3076470 to your computer and use it in GitHub Desktop.
MiniProfiler.Windows IOC and AOP
private static void ConfigureIocAndAop()
{
var builder = new ContainerBuilder();
//If using an IOC container, it is a handy to be able to us an IProfiler to
//wrap mini profiler calls just to remove that dependency for unit testing
builder.RegisterType<MiniProfilerWrapper>().AsImplementedInterfaces();
//We want some classes that do some work, but we don't want to have to wrap profiler steps
//around each method call, so use AOP to do it for us!
SnapConfiguration.For(new AutofacAspectContainer(builder)).
Configure(c =>
{
c.IncludeNamespace("ConsoleApplicationWithIocAndAop.*");
c.Bind<ProfileMethodInterceptor>().To<ProfileMethodAttribute>();
});
//Register the types we need to run the application
builder.RegisterType<DoQuickWork>().AsImplementedInterfaces();
builder.RegisterType<DoSlowWork>().AsImplementedInterfaces();
builder.RegisterType<ConsoleApplication>().AsImplementedInterfaces();
//Ensure we get useful type load exceptions: http://stackoverflow.com/a/8978721/281177
try
{
_container = builder.Build();
}
catch (Exception ex)
{
if (ex is ReflectionTypeLoadException)
{
var typeLoadException = ex as ReflectionTypeLoadException;
var loaderExceptions = typeLoadException.LoaderExceptions;
throw new AggregateException(typeLoadException.Message, loaderExceptions);
}
throw;
}
}
using Snap;
namespace ConsoleApplicationWithIocAndAop.AOP
{
public class ProfileMethodAttribute : MethodInterceptAttribute
{
}
}
using System;
using System.Reflection;
using Castle.DynamicProxy;
using Snap;
using StackExchange.Profiling;
namespace ConsoleApplicationWithIocAndAop.AOP
{
public class ProfileMethodInterceptor : MethodInterceptor
{
public override void InterceptMethod(IInvocation invocation, MethodBase method, Attribute attribute)
{
//Wrap each method call with a profiler step, using the method name as the step name
using (StackExchange.Profiling.MiniProfiler.Current.Step(method.Name))
{
invocation.Proceed();
}
}
}
}
private static void Main(string[] args)
{
//Configure building blocks
ConfigureIocAndAop();
//Start profiling
ConsoleProfiling.Start();
//Run the application, the log is all behind the IConsoleApplication's Run method so it can be easily unit tested
var app = _container.Resolve<IConsoleApplication>();
app.Run();
//Stop profiling and show results
Console.WriteLine(ConsoleProfiling.StopAndGetConsoleFriendlyOutputStringWithSqlTimings());
//Allow viewing of results
Console.WriteLine("... press 'Enter' to exit process ...");
Console.ReadLine();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment