AOP through Unity interceptors - Performance monitoring
Today we continue the serie on AOP with Performance monitoring.
The principle is very simple: we want to monitor the time a method took to execute.
Here is the code of the class.
As always, you need to specify that you want to use the behavior:
The principle is very simple: we want to monitor the time a method took to execute.
Here is the code of the class.
public class PerformanceMonitoringInterceptionBehavior : IInterceptionBehavior
{
public IEnumerable<Type> GetRequiredInterfaces()
{
return Type.EmptyTypes;
}
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
Stopwatch sw = Stopwatch.StartNew();
var result = getNext()(input, getNext);
sw.Stop();
WriteLog(String.Format("Method {0} took {1} ms", input.MethodBase, sw.ElapsedMilliseconds));
return result;
}
public bool WillExecute
{
get { return true; }
}
private void WriteLog(string message, string args = null)
{
var utcNow = DateTime.UtcNow;
Console.WriteLine(
"[{0}]-[{1}]: {2} {3}",
utcNow.ToShortDateString(),
utcNow.ToLongTimeString(),
message,
args);
}
}
As you can see, we only start & stop a Stopwatch to watch the time consumed by the method.As always, you need to specify that you want to use the behavior:
container.RegisterType<IStore, StoreImpl>( new Interceptor<InterfaceInterceptor>(), new InterceptionBehavior<PerformanceMonitoringInterceptionBehavior>()); container.RegisterType<IFoo, FooImpl>( new Interceptor<InterfaceInterceptor>(), new InterceptionBehavior<PerformanceMonitoringInterceptionBehavior>());
Comments
Post a Comment