使用 StructureMap 进行 AOP 日志记录 [英] AOP Logging with StructureMap

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

问题描述

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

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

基本上,我想做Castle, AOP and Logging在 .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:

创建一个城堡代理拦截器:

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

在您的 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天全站免登陆