Committed to Code

Castle aspires to simplify the development of enterprise and web applications. Offering a set of tools (working together or independently) and integration with other open source projects, Castle helps you get more done with less code.

Code Analysis


Recent Highlights

Anon32

Large commit — Merge pull request #3 from sharpjs/sharpjs

More than 1000 lines of source code were added or removed in this commit.

In commit bd8fdf37 by Craig Neuwirt on 2011-12-06 (6 months ago)

Anon32

Large commit — Added WeakKeyDictionary

More than 1000 lines of source code were added or removed in this commit.

In commit b4d2661e by Jeff Sharp on 2011-11-29 (6 months ago)

Anon32

Large commit — - added newly arrived projects to the solution

More than 1000 lines of source code were added or removed in this commit.

In commit 735c575b by Krzysztof Koźmic (Using name ‘Krzysztof Kozmic’) on 2011-11-07 (7 months ago)

Anon32

Large commit — - moved newly added facilities to where all the...

More than 1000 lines of source code were added or removed in this commit.

In commit 4b8e94f6 by Krzysztof Koźmic (Using name ‘Krzysztof Kozmic’) on 2011-11-07 (7 months ago)

Anon32

Large commit — - removed duplicate files

More than 1000 lines of source code were added or removed in this commit.

In commit ada47d39 by Krzysztof Koźmic (Using name ‘Krzysztof Kozmic’) on 2011-11-07 (7 months ago)

See all highlights…


News

Wiring HttpControllerContext With Castle Windsor

In a previous post I demonstrated how to wire up HttpControllerContext with Poor Man's DI. In this article I'll show how to wire up HttpControllerContext with Castle Windsor.

This turns out to be remarkably difficult, at least with the ... [More] constraints I tend to set for myself:

Readers of this blog may have an inkling that I have an absolute abhorrence of static state, so anything relying on that is out of the question. In addition to that, I also prefer to leverage the container as much as possible, so I'm not keen on duplicating a responsibility that really belongs to the container. No injecting the container into itself. That's just unnatural and lewd (without being fun). If possible, the solution should be thread-safe. The overall solution should still adhere to the Register Resolve Release pattern, so registering a captured HttpControllerContext is a no-go. It's also unlikely to work, since you'd need to somehow scope each registered instance to its source request. That also rules out nested containers. OK, so given these constraints, how can an object graph like this one be created, only with Castle Windsor instead of Poor Man's DI?

return new CatalogController(    new RouteLinker(        baseUri,        controllerContext));
Somehow, the HttpControllerContext instance must be captured and made available for further resolution of a CatalogController instance.

Capturing the HttpControllerContext

The first step is to capture the HttpControllerContext instance, as early as possible. From my previous post it should be reasonably clear that the best place to capture this instance is from within IHttpControllerActivator.Create.

Here's the requirement: the HttpControllerContext instance must be captured and made available for further resolution of the object graph – preferably in a thread-safe manner. Ideally, it should be captured in a thread-safe object that can start out uninitialized, but then allow exactly one assignment of a value.

At the time I first struggled with this, I was just finishing The Joy of Clojure, so this sounded to me an awful lot like the description of a promise. Crowdsourcing on Twitter turned up that the .NET equivalent of a promise is TaskCompletionSource<T>.

Creating a custom IHttpControllerActivator with an injected TaskCompletionSource<HttpControllerContext> sounds like a good approach. If the custom IHttpControllerActivator can be scoped to a specific request, that would be the solution then and there.

However, as I've previously described, the current incarnation of the ASP.NET Web API has the unfortunate behavior that all framework Services (such as IHttpControllerActivator) are resolved once and cached forever (effectively turning them into having the Singleton lifestyle, despite what you may attempt to configure in your container).

With Dependency Injection, the common solution to bridge the gap between a long-lasting lifestyle and a shorter lifestyle is a factory.

Thus, instead of injecting TaskCompletionSource<HttpControllerContext> into a custom IHttpControllerActivator, a Func<TaskCompletionSource<HttpControllerContext>> can be injected to bridge the lifestyle gap.

One other thing: the custom IHttpControllerActivator is only required to capture the HttpControllerContext for further reference, so I don't want to reimplement all the functionality of DefaultHttpControllerActivator. This is the reason why the custom IHttpControllerActivator ends up being a Decorator:

public class ContextCapturingControllerActivator :    IHttpControllerActivator{    private readonly IHttpControllerActivator activator;    private readonly Func<TaskCompletionSource<HttpControllerContext>>        promiseFactory;     public ContextCapturingControllerActivator(        Func<TaskCompletionSource<HttpControllerContext>> promiseFactory,        IHttpControllerActivator activator)    {        this.activator = activator;        this.promiseFactory = promiseFactory;    }     public IHttpController Create(        HttpControllerContext controllerContext,        Type controllerType)    {        this.promiseFactory().SetResult(controllerContext);        return this.activator.Create(controllerContext, controllerType);    }}
The ContextCapturingControllerActivator class simply Decorates another IHttpControllerActivator and does one thing before delegating the call to the inner implementation: it uses the factory to create a new instance of TaskCompletionSource<HttpControllerContext> and assigns the HttpControllerContext instance to that promise.

Scoping

Because the Web API is basically being an ass (I can write this here, because I'm gambling that the solitary reader making it this far is so desperate that he or she is not going to care about the swearing) by treating framework Services as Singletons, it doesn't matter how it's being registered:

container.Register(Component    .For<IHttpControllerActivator>()    .ImplementedBy<ContextCapturingControllerActivator>());container.Register(Component    .For<IHttpControllerActivator>()    .ImplementedBy<DefaultHttpControllerActivator>());
Notice that because Castle Windsor is being such an awesome library that it implicitly understands the Decorator pattern, I can simple register both Decorator and Decoratee in an ordered sequence.

The factory itself must also be registered as a Singleton (the default in Castle Windsor):

container.Register(Component    .For<Func<TaskCompletionSource<HttpControllerContext>>>()    .AsFactory());
Here, I'm taking advantage of Castle Windsor's Typed Factory Facility, so I'm simply asking it to treat a Func<TaskCompletionSource<HttpControllerContext>> as an Abstract Factory. Doing that means that every time the delegate is being invoked, Castle Windsor will create an instance of TaskCompletionSource<HttpControllerContext> with the correct lifetime.

This provides the bridge from Singleton lifestyle to PerWebRequest:

container.Register(Component    .For<TaskCompletionSource<HttpControllerContext>>()    .LifestylePerWebRequest());
Notice that TaskCompletionSource<HttpControllerContext> is registered with a PerWebRequest lifestyle, which means that every time the above delegate is invoked, it's going to create an instance which is scoped to the current request. This is exactly the desired behavior.

Registering HttpControllerContext

The only thing left is registering the HttpControllerContext class itself:

container.Register(Component    .For<HttpControllerContext>()    .UsingFactoryMethod(k =>         k.Resolve<TaskCompletionSource<HttpControllerContext>>()            .Task.Result)    .LifestylePerWebRequest());
This defines that HttpControllerContext instances are going to be resolved the following way: each time an HttpControllerContext instance is requested, the container is going to look up a TaskCompletionSource<HttpControllerContext> and return the result from that task.

The TaskCompletionSource<HttpControllerContext> instance is scoped per web request and previously captured (as you may recall) by the ContextCapturingControllerActivator class.

That's all (sic!) there's to it :) [Less]


Implementing an Abstract Factory

Abstract Factory is a tremendously useful pattern when used with Dependency Injection (DI). While I’ve repeatedly described how it can be used to solve various problems in DI, apparently I’ve never described how to implement one. As a comment to ... [More] an older blog post of mine, Thomas Jaskula asks how I’d implement the IOrderShipperFactory.

To stay consistent with the old order shipper scenario, this blog post outlines three alternative ways to implement the IOrderShipperFactory interface.

To make it a bit more challenging, the implementation should create instances of the OrderShipper2 class, which itself has a dependency:

public class OrderShipper2 : IOrderShipper{    private readonly IChannel channel;     public OrderShipper2(IChannel channel)    {        if (channel == null)            throw new ArgumentNullException("channel");         this.channel = channel;    }     public void Ship(Order order)    {        // Ship the order and        // raise a domain event over this.channel    }}
In order to be able to create an instance of OrderShipper2, any factory implementation must be able to supply an IChannel instance.

Manually Coded Factory

The first option is to manually wire up the OrderShipper2 instance within the factory:

public class ManualOrderShipperFactory :    IOrderShipperFactory{    private readonly IChannel channel;     public ManualOrderShipperFactory(IChannel channel)    {        if (channel == null)            throw new ArgumentNullException("channel");         this.channel = channel;    }     public IOrderShipper Create()    {        return new OrderShipper2(this.channel);    }}
This has the advantage that it’s easy to understand. It can be unit tested and implemented in the same library that also contains OrderShipper2 itself. This means that any client of that library is supplied with a read-to-use implementation.

The disadvantage of this approach is that if/when the constructor of OrderShipper2 changes, the ManualOrderShipperFactory class must also be corrected. Pragmatically, this may not be a big deal, but one could successfully argue that this violates the Open/Closed Principle.

Container-based Factory

Another option is to make the implementation a thin Adapter over a DI Container – in this example Castle Windsor:

public class ContainerFactory : IOrderShipperFactory{    private IWindsorContainer container;     public ContainerFactory(IWindsorContainer container)    {        if (container == null)            throw new ArgumentNullException("container");         this.container = container;    }     public IOrderShipper Create()    {        return this.container.Resolve<IOrderShipper>();    }}
But wait! Isn’t this an application of the Service Locator anti-pattern? Not if this class is part of the Composition Root.

If this implementation was placed in the same library as OrderShipper2 itself, it would mean that the library would have a hard dependency on the container. In such a case, it would certainly be a Service Locator.

However, when a Composition Root already references a container, it makes sense to place the ContainerFactory class there. This changes its role to the pure infrastructure component it really ought to be. This seems more SOLID, but the disadvantage is that there’s no longer a ready-to-use implementation packaged together with the LazyOrderShipper2 class. All new clients must supply their own implementation.

Dynamic Proxy

The third option is to basically reduce the principle behind the container-based factory to its core. Why bother writing even a thin Adapter if one can be automatically generated.

With Castle Windsor, the Typed Factory Facility makes this possible:

container.AddFacility<TypedFactoryFacility>();container.Register(Component    .For<IOrderShipperFactory>()    .AsFactory());var factory =    container.Resolve<IOrderShipperFactory>();
There is no longer any code which implements IOrderShipperFactory. Instead, a class conceptually similar to the ContainerFactory class above is dynamically generated and emitted at runtime.

While the code never materializes, conceptually, such a dynamically emitted implementation is still part of the Composition Root.

This approach has the advantage that it’s very DRY, but the disadvantages are similar to the container-based implementation above: there’s no longer a ready-to-use implementation. There’s also the additional disadvantage that out of the three alternative here outlined, the proxy-based implementation is the most difficult to understand. [Less]


MR3 – *very* high level overview

Picture = thousands of words, right?


Castle.Extensibility

One of the good things – of a few – of my tenure at the CLR team was being exposed to the metal. One of my interest areas was the loader, PM’ed by one of the most arrogant person I’ve ever met. Fortunately the senior dev in charge of it is an awesome person, and [...]


Castle Windsor 3.0 is released



After successful beta and RC releases final version of Castle Windsor (as well as Castle Core, and a whole set of facilities) has now been released. There are no major changes between final version and RC. The difference is some minor bug ... [More] fixes, improved exception messages and some small improvements all over the place.

 

The packages are available now, on Nuget (with symbols), and via standard .zip download.

 

Last but not least — thank you to everyone who downloaded beta and release candidate and provided feedback. You guys rock. [Less]


Read all Castle articles…

Edit RSS feeds.