inversion-of-control - AOP 使用 Windsor 和批量注册类

标签 inversion-of-control castle-windsor aop

我正在尝试配置一个应用程序,以便我的控制台可以使用来自 assemblyA 的类型来允许以 AOP 样式登录。 JournalInterceptor 只会将方法调用、输入和输出参数写到日志文件或某种数据存储中。

我一次可以注册一种类型,但我想一次性注册所有类型。一旦开始,我可能会向已注册的类型添加一些过滤,但我遗漏了一些东西。

我正在尝试使用 Classes.FromAssemblyContaining 但我不确定如何获取 IRegistration 实例以调用 WindsorContainer::Register

有什么线索吗?

// otherAssembly.cs
namespace assemblyA
{
  public class Foo1 { public virtual void What(){} }
  public class Foo2 { public virtual void Where(){} }
}
// program.cs
namespace console
{
  using assemblyA;

  public class JournalInterceptor : IInterceptor {}

  public class Program
  {
     public static void Main()
     {
        var container = new Castle.Windsor.WindsorContainer()
            .Register(
                Component.For<JournalInterceptor>().LifeStyle.Transient,
                // works but can't be the best way
                Component.For<Foo1>().LifeStyle.Transient
                    .Interceptors<JournalInterceptor>(),
                Component.For<Foo2>().LifeStyle.Transient,
                    .Interceptors<JournalInterceptor>(),
                // how do I do it this way
                Classes.FromAssemblyContaining<Foo1>()
                        .Pick()
                        .LifestyleTransient()
                        .Interceptors<JournalInterceptor>()
                      );

        Foo1 foo = container.Resolve<Foo1>();
     }
  }
}

最佳答案

实现 Pointcut .在 CaSTLe Windsor 中,这是通过实现 IModelInterceptorsSelector 接口(interface)来完成的。

它会是这样的:

public class JournalPointcut : IModelInterceptorsSelector
{
    public bool HasInterceptors(ComponentModel model)
    {
        return true; // intercept everything - probably not a good idea, though
    }

    public InterceptorReference[] SelectInterceptors(
        ComponentModel model, InterceptorReference[] interceptors)
    {
        return new[] 
        {
            InterceptorReference.ForType<JournalInterceptor>()
        }.Concat(interceptors).ToArray();
    }
}

然后向容器注册Interceptor和Pointcut:

this.container.Register(Component.For<JounalInterceptor>());

this.container.Kernel.ProxyFactory.AddInterceptorSelector(new JournalPointcut());

更深入的解释,你可能想看this recording .

关于inversion-of-control - AOP 使用 Windsor 和批量注册类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8713561/

相关文章:

c# - PostSharp 问题无法找到 system.web.mvc 的程序集,版本 = 3.0.0.0 当没有项目引用它时

java - 面向方面的编程 - 什么是 'cflow' ?

java - 如何使用 aspectJ 快速修改已编译的 java 类行为

dependency-injection - 为什么 Simple Injector 没有像 Unity 这样的 IContainer 抽象?

inversion-of-control - 为延迟加载注入(inject)数据访问依赖项的正确方法是什么?

.net - 我应该在自己的非 LINQ 代码中使用 DuplicateKeyException 吗?

.net - 我应该使用哪种依赖注入(inject)工具?

dependency-injection - 是什么让 IoC 容器成为 IoC 容器?

c# - CaSTLe Windsor IoC 属性注入(inject)简单操作方法

c# - 注册默认的 CaSTLe Windsor 组件,同时允许自定义组件