AOP与温莎城堡

时间:2012-07-27 15:09:34

标签: castle-windsor castle-dynamicproxy aop windsor-3.0

我想要实现的是通过使用Castle Windsor拦截器的属性进行AOP。我已经取得了一些成功,但在课堂级别与方法级别方面存在问题。

  • 如果我只使用类级别属性,则会拦截所有方法。
  • 如果我只使用方法级别属性,则会拦截这些方法。
  • 如果我添加了一个类级别属性和一个方法级别属性,那么两个拦截都会发生在被归属的方法上,但那些不会被拦截的方法。

所以给定了这个组件:

public interface IMyComponent
{
    void ShouldBeInterceptedByStopWatch_AND_ExceptionLogger();
    void ShouldBeInterceptedByExceptionLogger();
}

[LogExceptionAspect]
public class MyComponent : IMyComponent
{
    [StopwatchAspect]
    public void ShouldBeInterceptedByStopWatch_AND_ExceptionLogger()
    {
        for (var i = 0; i < 2; i++) Thread.Sleep(1000);
    }

    public void ShouldBeInterceptedByExceptionLogger()
    {
        throw new NotImplementedException();
    }
}

我希望记录器方面可以截取ShouldBeInterceptedByExceptionLogger(),但除非我从其他方法中删除秒表方面,否则它不会发生,或者从类中删除记录器方面并将其添加到ShouldBeInterceptedByExceptionLogger()。但ShouldBeInterceptedByStopWatch_AND_ExceptionLogger()被两者截获。

可以在以下位置找到整个示例应用程序   - https://bitbucket.org/jayala/juggernet-aop

基本上它正在使用一个工具来注册IContributeComponentModelConstruction,如果它在类级别找到一个方面,它将添加一个拦截器,或者如果它在方法级别找到方面,则添加一个拦截器+方法钩子。

这是我引导容器的方式:

        var container = new WindsorContainer()
            .AddFacility<LogExceptionAspectFacility>()
            .AddFacility<StopwatchAspectFacility>()
            .Register(Component
                .For<IMyComponent>()
                .ImplementedBy<MyComponent>()
                .LifeStyle.Transient);

设施正在做的是注册这样的拦截器和模型贡献者

public abstract class BaseAspectFacility<TAspectAttribute, TAspectInterceptor> : AbstractFacility
    where TAspectAttribute : Attribute
    where TAspectInterceptor : IInterceptor
{
    protected override void Init()
    {
        var interceptorName = Guid.NewGuid().ToString();
        Kernel.Register(Component.For<IInterceptor>()
                                 .Named(interceptorName)
                                 .ImplementedBy<TAspectInterceptor>()
                                 .LifeStyle.Singleton);
        var contributor = new ContributeAspectToModel<TAspectAttribute>(interceptorName);
        Kernel.ComponentModelBuilder.AddContributor(contributor);
    }
}

0 个答案:

没有答案