Search code examples
castle-windsorinterceptor

Registering an Interceptor For All Interface Implementations in Castle Windsor


I'm fairly new to Castle Windsor and in particular using Interceptors and am wondering if it is possible to register an Interceptor across all implementations of a particular interface without specifying each implementation in turn. For example, I have an interface called IComponent which will be implemented by a number of classes. I have a ComponentInterceptor class written to act on these classes when they have executed a particular method. I would like to do something like:

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

Rather than having to do:

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

Solution

  • I found another approach, I wanted to register this interceptor for all components being registered and do this hopefully minimal fuss. To do this I follow this article and created a new class like this:

    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>());
            }
        }
    }
    

    and then add this contribute with the Castle Windsor container

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