Created
July 20, 2012 15:22
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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