AOP Logging with StructureMap

被刻印的时光 ゝ 提交于 2020-01-14 03:26:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!