使用StructureMap记录AOP [英] AOP Logging with StructureMap

查看:157
本文介绍了使用StructureMap记录AOP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过StructureMap的AOP方法实现简单的日志记录.

I am trying to implement simple logging with AOP approach with StructureMap.

基本上,我想做城堡,AOP和日志记录中的问题在.NET 中使用StructureMap.

Basically, I want to do what is asked in the question Castle, AOP and Logging in .NET with StructureMap.

CastleWindsor具有有用的IInterceptor,您可以实现它,然后控制何时使用IInvocation.Proceed()调用a方法.允许您在调用该方法之前和之后执行日志记录.

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.

如何使用StructureMap做到这一点?我已经厌倦了使用自定义的Interceptor,但是您获得的唯一句柄是在创建实例时,而不是在实例上调用方法时.

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.

推荐答案

类似的方法可能对您有用:

Something like this would probably work for you:

创建城堡代理拦截器:

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);
    }
}

在您的SM配置中注册,以使用代理包装所有IFoo:

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())));

IFoo的所有实例上对任何方法的所有调用现在都将被LoggingInterceptor拦截.您当然可以通过检查实例来过滤要记录的呼叫.

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.

这篇关于使用StructureMap记录AOP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆