【问题标题】:Interceptor not working, how to debug them拦截器不工作,如何调试它们
【发布时间】:2015-08-16 19:58:39
【问题描述】:

我正在尝试让 Castle Windsor 使用我指定的拦截器。

这是我的代码:

container = new WindsorContainer();
container.AddFacility<TypedFactoryFacility>();

container.Register(Castle.MicroKernel.Registration
   .Types
   .FromThisAssembly()
   .BasedOn<IInterceptor>()
   .Configure(x=>x.LifestyleTransient()));               

container.Register(Castle.MicroKernel.Registration
   .Types
   .FromAssemblyInThisApplication()
   .BasedOn<IImporter>()
   .Configure(x => x.Interceptors<LoggingInterceptor>().LifeStyle.Is(LifestyleType.Transient)));

container.Register(Component
  .For<IImporterFactory>()
  .AsFactory(c => c.SelectedWith(new ImporterFactoryComponentSelector()))
  .LifeStyle.Transient);

设置 Castle Windsor 后,我得到了我需要的 IImporter 实现:

IImporterFactory importerFactory = container.Resolve<IImporterFactory>();
var test = importerFactory.Create(FileType.M3Availability);
test.ImportFile(fileName);

我希望在执行 test.ImportFile(str) 之前调用拦截器,但它不是

我在组件注册过程中做错了吗?

查看“容器”对象我可以看到我所有的对象都有正确的拦截器(见图)

我在组件注册期间做错了吗? 我该如何调试?

【问题讨论】:

  • 您的拦截器是否注册了 LoggingInterceptor 服务?你能从容器中解析那个类型吗?

标签: castle-windsor castle-dynamicproxy


【解决方案1】:

Windsor 只能拦截虚拟方法和接口。在您的实例中,您正在尝试解析具体类型,而 windsor 无法装饰它们。

解决方案是用接口注册IImporter,并将每个实例命名为具体实现的名称。

更新

WithServiceAllInterfaces 应该注册所有接口而不是类。

.Named(c.Implementation.Name) 应该使用具体类型的名称注册接口,以便您可以在选择器中使用具体类型的名称。

您在注册时需要更改的内容:

container.Register(Castle.MicroKernel.Registration
    .Classes
    .FromAssemblyInThisApplication()
    .BasedOn<IImporter>()
    .WithServiceAllInterfaces()
    .Configure(c => 
        c.Interceptors<LoggingInterceptor>()
        .LifeStyle.Is(LifestyleType.Transient).Named(c.Implementation.Name)));

我在你的代码上试过这个,这很有效。

【讨论】:

  • 嗨 Jakob,我已经尝试过您的解决方案,但它不起作用。如果我将我的方法标记为虚拟,则会调用拦截器。但是 IImporter 是一个接口,实际上它是我所有导入器的接口(它们是使用 IImporterFactory 选择的),所以它确实应该工作。注册我的所有进口商类别的最佳方式是什么?我认为使用 BasedOn() 没问题。谢谢!
  • 您的注册很好,但您的实现正在注册具体类型,如果您的 IImporter 类仅实现一个接口或者它是第一个接口,您可以尝试使用 WithServiceDefaultInterfaces。然后您还必须将名称注册为类名,这样您才能解析接口而不是具体类型。
  • 你是对的@Jakob。我唯一的建议是我会避开WithServiceFirstInterface,而是根据情况使用WithServiceBaseWithServiceAllInterfaces
  • 谢谢@KrzysztofKozmic,这似乎更合适。我会更新我的答案。
猜你喜欢
  • 2014-02-11
  • 1970-01-01
  • 1970-01-01
  • 2012-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-14
  • 2019-08-03
相关资源
最近更新 更多