Choose Between IInterceptorSelector and IModelInterceptorsSelector in Castle Windsor

18 May 2015

Interceptors in Castle Windsor are one of the easiest and most powerful constructs within the framework. Interceptors make it almost trivial to implement cross-cutting concerns such as logging or error handling, but really give you a way to share almost any logic across types with almost no ongoing maintenance burden. And typically this begins with an interceptor that should always be applied to a given component and such a registration is very easy:


container.Register(Component.For<IMyService>().ImplementedBy<TheService>().Interceptors(typeof(MyInterceptor)));

Suppose, though, we want to determine at runtime whether an interceptor should be applied? For example, what if a configuration setting allows us to toggle the interceptor on and off - how would we handle that? Well of course the brute force way is:


var enableInterceptor = GetConfigSettingOnOffState();

if (enableInterceptor)
	container.Register(Component.For<IMyService>().ImplementedBy<TheService>().Interceptors(typeof(MyInterceptor)));
else 
	container.Register(Component.For<IMyService>().ImplementedBy<TheService>());

That certainly does the job, but it’s ugly. We’re duplicating our registration, which adds to the maintenance burden. The good news: there is a better way! The bad news: there are two similarly-named interfaces, IInterceptorSelector and IModelInterceptorsSelector: how do we know which one to use?

For the purpose of this post, let’s split our access to the Windsor container into two separate categories. The first phase we will call registration time and this is the time from when the Windsor container is first constructed until the application is ready to begin handling results. During the registration period, we are actively modifying the container with new component registrations. The second phase we will call resolution time and this is from when our application begins handling requests until the application terminates. In this phase, we are no longer modifying the container, but instead it is servicing our application by resolving components upon request (such as in response to HTTP requests or messages). Using these two phases makes it easier to differentiate these two interfaces.

The other key thing to remember is how interceptors are implemented: they are generated by the Castle DynamicProxy library as necessary when the container is resolving a service. If a component has interceptors applied, the container requests DynamicProxy construct proxy instances that contain the interceptor functionality.

Implementing IModelInterceptorsSelector

Here is a sample IModelInterceptorsSelector:


 public class MyInterceptorSelector : IModelInterceptorsSelector
    {
		private readonly bool interceptorEnabled;
	
		public MyInterceptorSelector()
		{
			this.interceptorEnabled = System.Configuration.ConfigurationManager.AppSettings["interceptorSetting"] == "yes";
		}
		
        public bool HasInterceptors(ComponentModel model)
        {     
			return model.Implementation == typeof(IMyService) && this.interceptorEnabled;		
        }

        public Castle.Core.InterceptorReference[] SelectInterceptors(ComponentModel model, 
                                                                    InterceptorReference[] interceptors)
        {
			return interceptors.Concat(new InterceptorReference(typeof(MyInterceptor)));
        }
    }
	
	/// Add interceptor selector into ProxyFactory on the container
	container.Kernel.ProxyFactory.AddInterceptorSelector(new MyInterceptorSelector());
	

So what’s going on here? First, HasInterceptors defines whether this selector wants to apply interceptors to the component model. Windsor will call this method for a given component model to decide if it should give the selector a chance to provide an interceptor. If it returns true, Windsor will later call SelectInterceptors. The collection of interceptors is all those interceptors that have previously been applied to the component model. The selector must return a collection of interceptors that should apply to the model. At a minimum, that means returning the interceptors argument as-is. However, typically the selector will add a new interceptor into the collection and return the modified one as shown. Note that InterceptorReference is the argument collection type and we instruct the constructed reference as to our interceptor type. In our case, HasInterceptors is based simply on whether the interceptor should be enabled and that the component model is for the type we care about (IMyService in this case). This is an important point: once we add the selector to the ProxyFactory, Windsor will call our selector for all new component models to give us a chance to specify if an interceptor should be applied to it. In SelectInterceptors, we simply append an InterceptorReference to our interceptor to the collection and return it.

From this, would we say this selector is registration-time or resolution-time? It’s a registration-time extension point and we can infer this from both its use of the component model as an argument plus the fact that it deals in InterceptorReference and not IInterceptor. Bottom-line: IModelInterceptorsSelector allows us to stipulate the default set of interceptors that should apply to a given component. We can add to this list, remove items from the list, or reorder them.

Implementing IInterceptorSelector

Here’s an IInterceptorSelector that achieves the same functional end as IModelInterceptorsSelector, but in a completely different way:


 public class MyInterceptorSelector : IInterceptorSelector
    {
        private readonly bool enableInterceptor;

        public MyInterceptorSelector()
        {
            this.enableInterceptor = System.Configuration.ConfigurationManager.AppSettings["enableMyInterceptor"] == "yes";
        }
        public IInterceptor[] SelectInterceptors(Type type, MethodInfo method, IInterceptor[] interceptors)
        {
           if (!enableInterceptor)
		   {
				return interceptors.Where(a => !a.GetType() == typeof(IMyService));
		   }
		   
		   return interceptors;
        }
    }

Now we’ve got one method to implement that takes a Type, a MethodInfo, and a collection of IInterceptors. The lattermost of these are “live” instances - they have been fully constructed by the container, but not yet executed. This immediately tells us that IInterceptorSelector is a resolution-time construct. Unlike IModelInterceptorsSelector, we no longer have the ability to add new interceptors to the collection as we do not have the means to construct an interceptor (other than manually, which if we’re using Windsor, is sort of defeating the purpose). What we can do is filter or reorder the collection of interceptors. In this case, we simply assess if the interceptor should be enabled and if not, we filter it out of the list of interceptors. Unsurprisingly, this is a resolution-time component, which we can determine based largely on the fact that we receive a collection of already-constructed interceptors. The other big point: this allows us to determine if an interceptor should only apply to some methods of a type, but not necessarily all.

So How Do I Choose?

If you want an interceptor to apply to all methods on a type, use an IModelInterceptorsSelector to specify that it is one of the default interceptors for the type. This is most likely to keep the proxy factory performance at a good level since proxies can be cached and reused since our logic applies at the InterceptorReference level prior to live instances being constructed.

If you want an interceptor to apply to a given type, but only to certain methods, IInterceptorSelector is your only choice between these two components since the other is at the model level, not the method level. Again, this could have performance impacts on the ability of proxies to be cached so be careful overusing this approach. If you find yourself doing method selection quite heavily, it might make more sense to have the actual IInterceptor instance perform its own check on the method (based on IInvocation passed to it). This muddies things a bit, but the performance gain may be substantial enough to justify it, particularly if you have a lot of IInterceptorSelectors performing per-method filtering.


Registering Decorators, Composites, and Chains in Castle Windsor

24 April 2015

As I show people Castle Windsor and how to unlock its power to write more loosely coupled components, most quickly grasp the idea of registering a single component type against a service. That’s certainly a necessary first step, but what I often see is once developers start using Windsor, the code-base explodes with violations of the Reused Abstractions Principle or the code base still contains the same tightly coupled logic that it always did. I’ve discussed in previous posts how to identify cases where a decorator, composite, or chain of responsibility can make a dramatic difference on a codebase, but I often see developers run into trouble registering components for these patterns in Windsor. And in fact I’ve had some developers tell me they abandoned that design simply because they couldn’t get it registered in Windsor. I found that wholly shocking that a tool we’re using that’s capable of loosening our coupling is contributing to making it worse. To rectify that, I’m going to demonstrate in this post some ways to compose these patterns in Windsor. Definitely read to the bottom though as ultimately there is one super-easy way to do it.

Chain of Responsibility

In a chain of responsibility, we have some number of components that all implement the same interface and each one is connected to one (or more) of the others. Clients call the first component in the chain and based on the logic of the overall chain sub-system, the component can take some action and/or forward it to the next component. Below is a basic set of components for a chain that we’ll use. In our case, clients would be handed an instance of FirstInChain, which would call SecondInChain, which would call LastInChain.


  public interface IChain
    {
        string Get();
    }

    public class FirstInChain : IChain
    {
        public FirstInChain(IChain next)
        {
            this.Next = next;
        }

        public string Get()
        {
            return this.Next.Get();
        }

        public IChain Next { get; private set; }
    }

    public class SecondInChain : IChain
    {
        public SecondInChain(IChain next)
        {
            this.Next = next;
        }

        public string Get()
        {
            return this.Next.Get();
        }

        public IChain Next { get; private set; }
    }

    public class LastInChain : IChain
    {
        public LastInChain()
        {        
        }

        public string Get()
        {
            return "I'm done";
        }        
    }
	

The most important rule to understand for these registrations is, by default, Windsor will use the first registration for a type to determine how the object graph is composed. Thus if we want to be given an instance of FirstInChain, it needs to be registered first;


	container.Register(Component.For<IChain>().ImplementedBy<FirstInChain>());

So now, if we call container.Resolve<IChain>(), we’ll get an instance of FirstInChain, but since Windsor doesn’t have way know what FirstInChain should be given (and it won’t give it an instance of itself), our chain is not properly composed. So how can we instruct Windsor about our dependencies from First->Second->Last? Well one way is through naming each component and specifying them as dependencies. Here’s a unit test that will showcase this. I have scrambled up the order of Second and Last to showcase that Windsor identifies the components using the specified dependency relationships.


  [Fact]
        public void Register_ChainOfResponsiblity_UsingDependencyOnComponent_ForNamedComponents()
        {
            var container = new WindsorContainer();

            container.Register(Component.For<IChain>().ImplementedBy<FirstInChain>().Named("first")
                                        .DependsOn(Dependency.OnComponent("next", "second")));

            container.Register(Component.For<IChain>().ImplementedBy<LastInChain>().Named("last"));			
			
            container.Register(Component.For<IChain>().ImplementedBy<SecondInChain>().Named("second")
                                        .DependsOn(Dependency.OnComponent("next", "last")));
                        
            var component = container.Resolve<IChain>();

            var first = Assert.IsType<FirstInChain>(component);
            var second = Assert.IsType<SecondInChain>(first.Next);
            var last = Assert.IsType<LastInChain>(second.Next);            
        }
		

The above is typically the first step most people make when trying to register these components. This will work fine, but it just feels a little ugly. How else could we do it? Here’s the amazing part of Windsor: it will compose the graph correctly, automatically, if you just order the components the way you want them to be resolved.


	[Fact]
    public void AutoWire_ChainOfResponsiblity_BasedOnRegistrationOrder()
    {
        var container = new WindsorContainer();

        container.Register(Component.For<IChain>().ImplementedBy<FirstInChain>(),                               
                           Component.For<IChain>().ImplementedBy<SecondInChain>(),
                           Component.For<IChain>().ImplementedBy<LastInChain>());
                            
        var component = container.Resolve<IChain>();

        var first = Assert.IsType<FirstInChain>(component);
        var second = Assert.IsType<SecondInChain>(first.Next);
        var last = Assert.IsType<LastInChain>(second.Next);
    }
		

The fact that Windsor will auto-wire this escaped me for quite a long time, but this is what makes Windsor so incredible: it just works.

The same is also true for the other design patterns as well.

Decorator

A decorator is a pattern where one component of an interface type relies on another instance of that component to do its work. For example, we may have a class that fetches records from a database and another that caches those records. The caching component can “decorate” its logic on top of the other component. Below is a sample set of components we’ll work with. We want SecondDecorator to be on top and contain an instance of FirstDecorator, which will contain an instance of BaseDecoratableService.


 public interface IDecoratableService
    {
        string Do();
    }

    public class BaseDecoratableService : IDecoratableService
    {
        public string Do()
        {
            return string.Empty;
        }
    }

    public class FirstDecorator : IDecoratableService
    {
        private readonly IDecoratableService inner;

        public FirstDecorator(IDecoratableService inner)
        {
            this.inner = inner;
        }

        public string Do()
        {
            return string.Concat(this.inner.Do(), "#FIRST#");
        }

        public IDecoratableService Inner { get { return this.inner; } }
    }

    public class SecondDecorator : IDecoratableService
    {
        private readonly IDecoratableService inner;

        public SecondDecorator(IDecoratableService inner)
        {
            this.inner = inner;
        }

        public string Do()
        {
            return string.Concat(this.inner.Do(), "@@SECOND@@");
        }

        public IDecoratableService Inner { get { return this.inner; } }
    }

The registrations for Windsor to auto-wire this are almost identical to the Chain:


    [Fact]
    public void AutoWire_Decorator()
    {
        var container = new WindsorContainer();

        container.Register(Component.For<IDecoratableService>().ImplementedBy<SecondDecorator>(),
                           Component.For<IDecoratableService>().ImplementedBy<FirstDecorator>(),
                           Component.For<IDecoratableService>().ImplementedBy<BaseDecoratableService>());       

        var service = container.Resolve<IDecoratableService>();

        var secondDecorator = Assert.IsType<SecondDecorator>(service);
        var firstDecorator = Assert.IsType<FirstDecorator>(secondDecorator.Inner);
		var baseService = Assert.IsType<BaseDecoratableService>(firstDecorator.Inner);
	}
	

Composite

A composite is a pattern where one component contains some number of instances of the same interface and depending on the logic, the composite may selectively call its contained components or call all of them. The complication for Windsor is that it needs to supply a collection of instances and not just a single instance. This requires us to add Windsor’s CollectionResolver (if it hasn’t been added previously), but otherwise is identical to the Chain and Decorator:


	public interface IComposableService
    {
        void Do(string s);
    }

    public class CompositeComposableService : IComposableService
    {
        public CompositeComposableService(params IComposableService[] services)
        {
            if (services == null)
                throw new ArgumentNullException("services");

            this.Services = services.ToList();
        }

        public void Do(string s)
        {
            this.Services.ToList().ForEach(a => a.Do(s));
        }

        public IList<IComposableService> Services { get; private set; }
    }

    public class FirstComposableService : IComposableService
    {
        public void Do(string s)
        {            
        }
    }

    public class SecondComposableService : IComposableService
    {
        public void Do(string s)
        {
        }
    }

	[Fact]
    public void AutoWire_Composite()
    {
        var container = new WindsorContainer();
        /// Must add the CollectionResolver or it will not work.
        container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));

        container.Register(Component.For<IComposableService>().ImplementedBy<CompositeComposableService>(),
                           Component.For<IComposableService>().ImplementedBy<FirstComposableService>(),
                           Component.For<IComposableService>().ImplementedBy<SecondComposableService>());

        var service = container.Resolve<IComposableService>();

        var composite = Assert.IsType<CompositeComposableService>(service);

        Assert.Equal(2, composite.Services.Count());
        Assert.True(composite.Services.Any(a => a.GetType() == typeof(FirstComposableService)));
        Assert.True(composite.Services.Any(a => a.GetType() == typeof(SecondComposableService)));
    }
	

Wrap Up

So there you have it: Windsor’s auto-wiring will automatically compose these 3 powerful patterns for you. In fact it takes more work to not just let Windsor handle this. Now yes, if you have some specialized resolution needs (such as you don’t always want every component to be put into the Composite or something like that), then you’ll have to do something extra, but otherwise, no longer any need to fear these patterns. In a future post, I’ll show how you can control conditional resolutions in Windsor as well for some more advanced scenarios.