AOP与温莎城堡

Jua*_*ala 5 aop castle-windsor castle-dynamicproxy 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望记录器方面可以拦截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);
Run Code Online (Sandbox Code Playgroud)

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)