2014-10-17 88 views
2

我對Castle Windsor相當陌生,特別是使用攔截器,並且想知道是否可以在特定接口的所有實現中註冊Interceptor,而無需依次指定每個實現。例如,我有一個名爲IComponent的接口,它將由許多類實現。我寫了一個ComponentInterceptor類,它們在執行特定方法時會對這些類執行操作。我想這樣做:爲溫莎城堡中的所有接口實現註冊攔截器

_container.Register(
Component.For<IComponent>() 
        .Interceptors("ComponentInterceptor") 
        .LifestyleSingleton()) 

而不是必須做的:

 _container.Register(
     Component.For<IComponent>() 
       .ImplementedBy<ComponentA>() 
       .Interceptors("ComponentInterceptor") 
       .LifestyleSingleton()), 
    _container.Register(
     Component.For<IComponent>() 
       .ImplementedBy<ComponentB>() 
       .Interceptors("ComponentInterceptor") 
       .LifestyleSingleton()) 

回答

2

我發現了另一種方法,我想爲所有正在註冊的組件註冊這個攔截器,並且希望這樣做可以做到最小化。要做到這一點我跟this article並創建了一個新的階級是這樣的:

public class MyContributeComponentConstruct : IContributeComponentModelConstruction 
{ 
    public void ProcessModel(IKernel kernel, ComponentModel model) 
    { 
     if (model.Services.Any(s => s == typeof(IComponent))) 
     { 
      model.Interceptors.Add(InterceptorReference.ForType<ComponentInterceptor>()); 
     } 
    } 
} 

,然後添加與溫莎城堡容器

container.Kernel.ComponentModelBuilder.AddContributor(new MyContributeComponentConstruct()); 
+1

一個貢獻者這有助於爲另一種方法。雖然你不應該得到處理程序並添加一個這樣的攔截器,因爲當每個組件註冊時都會調用這個攔截器。你應該只修改提供的'model',否則你的組件將獲得攔截器的多個實例。我已經更新了你的答案以反映這一點。 – 2014-10-17 14:29:54

2

您可以在容器中通過Classes類使用約定註冊組件。以下寄存器該服務IComponent下,並與您ComponentInterceptor攔截器實現IComponent所有類在當前彙編:

container.Register(
    Classes.FromThisAssembly() 
     .BasedOn<IComponent>() 
     .WithService.FromInterface() 
     .Configure(c => c.Interceptors<ComponentInterceptor>()) 
); 

Windsor documentation提供了一系列的其他例子,並詳細解釋了不同類別是。