问题
I am trying to implement simple logging with AOP approach with StructureMap.
Basically, I want to do what is asked in the question Castle, AOP and Logging in .NET with StructureMap.
CastleWindsor has the helpful IInterceptor
that you can implement and then control when the a method is called with the IInvocation.Proceed()
. Allowing you to perform logging before and after the call to the method is made.
How can achieve this with StructureMap? I have tired using a custom Interceptor
but the only handle you get is when the instance is created, not when a method is called on the instance.
回答1:
Something like this would probably work for you:
Create a castle proxy interceptor:
public class LoggingInterceptor : IInterceptor
{
private readonly IMyLogger _logger;
public LoggingInterceptor(IMyLogger logger) { _logger = logger; }
public void Intercept(IInvocation invocation)
{
_logger.Log("Before calling " + invocation.Method);
invocation.Proceed();
_logger.Log("After calling " + invocation.Method);
}
}
Register this in you SM configuration to wrap all IFoo
with a proxy:
var proxyGenerator = new ProxyGenerator();
c.For<IFoo>().Use<Foo>();
c.For<IFoo>()
.EnrichAllWith(instance =>
proxyGenerator.CreateInterfaceProxyWithTarget<IFoo>(instance,
new LoggingInterceptor(new MyLogger())));
All calls to any method on all instances of IFoo
will now be intercepted by the LoggingInterceptor
. You can of course filter which calls you want to log by inspecting the instance.
来源:https://stackoverflow.com/questions/13745629/aop-logging-with-structuremap