Skip to content

Instantly share code, notes, and snippets.

@cairey
Created July 20, 2012 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cairey/3151305 to your computer and use it in GitHub Desktop.
Save cairey/3151305 to your computer and use it in GitHub Desktop.
Aspect Oriented Programming with MEF using the interceptors. Compose an interceptor catalog in the example below
private static void Compose()
{
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new DirectoryCatalog(@".\bin"));
var cfg = new InterceptionConfiguration()
.AddInterceptor(new DynamicProxyInterceptor(new LogInterceptor()));
var interceptingCatalog = new InterceptingCatalog(catalog, cfg);
Container = new CompositionContainer(interceptingCatalog);
}
public class LogInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
if(invocation.TargetType.GetCustomAttributes(typeof(LogMethodCallsAttribute), true).Length > 0)
{
var loggerFacade = MefInstanceProvider.Container.GetExportedValue<ILoggerFacade>();
loggerFacade.Log(FormatMethodCall(invocation, ApplicationStates.Started), Category.Info, Priority.Low);
invocation.Proceed();
loggerFacade.Log(FormatMethodCall(invocation, ApplicationStates.Ended), Category.Info, Priority.Low);
return;
}
invocation.Proceed();
}
private static string FormatMethodCall(IInvocation invocation, ApplicationStates state)
{
var message = invocation.InvocationTarget.GetType().Name + " Call " + state + ": ";
var result = invocation.Method.Name;
result += "(";
foreach(var parameter in invocation.Method.GetParameters())
{
result += parameter.ParameterType.Name + " " + parameter.Name + ", ";
}
result = result.Remove(result.Length - 2);
result += ")";
return message + result;
}
}
/// <summary>
/// Used by the MEF Interceptors
/// </summary>
public class LogMethodCallsAttribute : Attribute {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment