Castle Windsor 2.5… the final countdown – beta 1 released (and Core, DynamicProxy, Dictionary Adapter)

Well it’s about time. Due to certain events (like me relocating to the other part of the world) it’s later than planned but it’s here – beta 1 of Castle Windsor 2.5 is available for download.

There’s been quite a lot of changes in the release. Not just in the code but in the entire Castle Project.

We migrated from Subversion to Git, and you can now access the repositories on github. Hopefully this will make things easier for anyone who wants to contribute features and patches to get going, and will raise the level of community contributions to the project (actually it already has, although not as much as I’d like).

We moved from out previous documentation to the new open wiki engine. The documentation is still being migrated and updated but I can say that for Windsor the documentation is already pretty complete and it covers all the new features in version 2.5. The wiki is open for anyone to register and contribute, either by proofreading and fixing spelling errors, expanding existing topics or adding new ones.

Also it’s worth mentioning the awesome work that Andy Pike’s been doing on CastleCasts. The website (built on Castle stack obviously) contains free short screencasts that will help you learn different aspects of the Castle stack. While most of the screncasts are dedicated to Monorail, Andy recently started covering Windsor as well. And the best part is – CastleCasts is an open place for Castle-related screencasts so if you want to record one, and share your knowledge with others go ahead.

What’s in it – Core (now incl. DynamicProxy and Dictionary Adapter)

Here are some of the highlights of the release for Castle.Core.dll

  • Castle.DynamicProxy.dll got now merged into Castle.Core.dll (same with Dictionary Adapter) so now you need to reference just single assembly instead of two.
  • Supports .NET 4 (and .NET 4 client profile)
  • DynamicProxy has now new kind of proxies – Class proxy with target. I blogged about limitations of this approach, so use this with caution
  • DynamicProxy will now let you intercept explicitly implemented interface methods on class proxy
  • DynamicProxy will now let you intercept calls to methods on System.Object (ToString, Equals, GetHashCode) – the default ProxyGenerationHook will still opt out of this though
  • Dictionary Adapter performance improvements.  Proxy class are cached so DA no longer traverses assemblies to find type
  • Dictionary Adapter automatic support for NotifyPropertyChanged. EditableObject, IDataErrorInfo, and validation capabilities.  Just extend from the interface(s) and feature is enabled
  • Dictionary Adapter support for custom HashCode/Equals strategy so you can better support persistence in which and Id usually used for equality
  • Ability to coerce one Dictionary Adapter into another and/or copy properties from one to another.
  • Integrated support for Xml/XPath using standard Xml Serialization attributes – this gives you strongly typed config files (for example)

Plus many more minor fixes, features and improvements. You can see the entire list in changelog.

What’s in it – Windsor

The main dish is obviously Windsor, and there are plenty interesting new features and improvements as well.

And heaps of other smaller improvements and general polish.

Breaking changes

This is a point-five release, which means it is highly compatible with previous release and upgrading should be pretty straightforward and quick. There are some changes though, and we tried to document all of them in breakingchanges.txt file included in the release. Read the file to see the list of breaking changes and upgrade path for each of them. If you find any breaking change not described in the file, or some information that is inaccurate of missing let us know, so that we can improve that for the final release.

In addition to that also some API was made obsolete in this release (most notably the old registration API) to discourage users from its usage. It is not going away anytime soon, but it is highly recommended to migrate code using the now-obsolete API to the alternatives.

What’s next

This is beta 1 release. It means that before the final release no new major features will be added and no breaking changes will be introduced (unless necessary to fix a critical bug, which is unlikely). This release contains only .NET version of Windsor. Version for Silverlight is still in works and will be part of beta 2 release. We’re also working on some sample applications to help you get started using Windsor. The samples will be also included in beta 2 release. So far we have a winforms sample almost ready. If you’d like to contribute a web sample feel more than welcome to contribute.

ETA for beta 2 is in two weeks, if no big issues are found, final release will be out around two weeks after.

Get it, play with it, give us your feedback!

The bits are here, to discuss the release go to our google users group.

New Castle Windsor feature – debugger diagnostics

What you’re seeing here, is a feature in very early stages of development. It’s very likely to change in the very near future, hopefully based on your feedback which I’m looking forward to.

It is often the case with IoC containers, especially when registering components by convention, that you end up with misconfigured components, or with an exception saying that your component can’t be resolved. To aid working in these situations StructureMap provides methods like WhatDoIHave and AssertConfigurationIsValid. That’s the only container I know of that provides this kind of diagnostics.

Windsor also has similar ability to StructureMap’s WhatDoIHave method. It’s very powerful as well, since Windsor tracks internally the entire graph of objects and lets you access it you can for example visualize it.

The AssertConfigurationIsValid is a tougher nut to crack. Thing is – you can’t really say when the configuration is valid in any non trivial situation. You can’t say when it’s non-valid either. The reason for that is that there are multiple dynamic moving parts that you can’t really statically analyse to output a yes/no value.

What Windsor does

To help with these situations when debugging, in Windsor 2.5 I added debugging proxies to the most important classes in Windsor, so that when looking at them in the debugger you will be presented with much more helpful view of what’s in the container and what’s potentially not right.

debugger_visualizer

You will see a very minimalistic view of what’s going on in the container:

  • All components – will give you a list of all existing components in the container, kind of like WhatDoIHave
  • Facilities will give you the list of the installed facilities
  • Potentially misconfigured components – this is a list of components that don’t look to good to Windsor and may have some dependencies missing. It also is a very simplified view. At the first glance it will only tell you the key of the component (in this case fully qualified name), slash service/implementation. In this case both service and implementation are the same, so it won’t repeat the information.
    When you drill down, you will also see the lifestyle of the component and most importantly its status, which will tell you why Windsor thinks there may be something wrong with the component.

debugger_visualizer2

This pretty nicely tells you what might be wrong. If you are sure you providing these values dynamically, be it from the call site or via dynamic parameters, you can move on, otherwise it can remind you of the missing dependencies.

I want your feedback

How do you like this feature? How would you change it? What other information you think would be useful in this view? Leave a comment, or go to uservoice site to share your ideas.

Thanks

How I use Inversion of Control containers – pulling from the container

As I expected my previous post prompted a few questions regarding the Three Container Calls pattern I outlined. Major one of them is how to handle the following scenario:

Container_pulling

We create our container, install all the components in it.  Moments later we resolve the root component, container goes and creates its entire tree of dependencies for us, does all the configuration and other bookkeeping, injects all the dependencies and gives us back the new fresh ready to use objects graph that we then use to start off the application.

More often than not, this will not be enough though. At some point later in the lifecycle of the application, a user comes in and wants something from the application. Lets say the user clicks a button saying “Open a file” and at this point a “OpenFile” view should be loaded along with all of its dependencies and presented to the user. But wait – it gets worse – Because now if a user selects a .txt file a “DisplayText” view should be loaded, but when a .png file gets selected, we should load a “DisplayImage” view.

Generalizing – how to handle situations where you need to request some dependencies unavailable at registration or root resolution time, potentially passing some parameters to the component to be resolved, or some contextual information affecting which component will be resolved (or both).

Factory alive and kicking

The way to tackle this is to use a very old design patterns (from the original GOF patterns book) called Abstract factory and Factory method.

Nitpickers’ corners – as I know I will be called out by some purists that what I’m describing here is not purely this or that pattern according to this or that definition  – I don’t care, so don’t bother. What’s important is the concept.

It gives us exactly what we need – provides us with some components on demand, allowing us to pass some inputs in, and on the same time encapsulating and abstracting how the object is constructed. The encapsulating part means that I totally don’t need to care about how, and where the components get created – it’s completely offloaded to the container. The abstracting part means that I can still adhere to the Matrix Principle – the spoon container does not exist.

How does this work?

Using Castle Windsor, this is very simple – all you have to do is to declare the factory interface, and Windsor itself will provide the implementation. It is very important. Your interface lives in your domain assembly, and knows nothing about Windsor. The implementation is a detail, which depends on the abstraction you provided, not the other way around. This also means that most of the time all of the work you have to do is simply declaring the interface, and leave all the heavy lifting to Windsor, which has some pretty smart defaults that it will use to figure this stuff out by itself. For non-standard cases, like deciding which component to load based on the extension of the file provided, you can easily extend the way factory works by using custom selector. With well thought out naming convention, customizing Windsor to support this scenario is literally one line of meaningful code.

In addition to that (although I prefer the interface-driven approach) Windsor (upcoming version 2.5), and some other containers, like Autofac (which first implemented the concept), and StructureMap (don’t really know about Ninject, perhaps someone can clarify this in the comments) support delegate based factories, where just the fact of having a dependency on Func<IFoo> is enough for the container to figure out that it should inject for that dependency a delegate that when invoked will call back to the container to resolve the IFoo service. The container will even implement the delegate for you, and it also obviously means that the code you have has no idea (nor does it care) that the actual dependency was created by a container.

 

This is the beauty of this approach – it has all the pros and none of the cons of Service Locator, and shift towards supporting it was one of the major changes in the .NET IoC backyard in the last couple of months, so if you are still using Service Locator you’re doing it wrong.

How I use Inversion of Control containers

Quite regularly I get asked by people how they should use IoC container in their application. I don’t think I can answer this question once and universally because every application is different, every application has different needs and every application has different opportunities for leveraging an Inversion of Control container.

However there are some general rules and patterns that I use and I thought I will blog about this instead.

While I use a concrete example of Castle Windsor, the discussion here is universal.It applies to all containers.

Inversion of Control means container does not exist

Container_does_not_exist

Basic difference between an Inversion of Control framework and any other kind of framework is that the control gets inverted. Your application does not call to the framework. Instead the framework is aware of your application and it goes and does its stuff with your application’s objects.

Since Inversion of Control Containers are Inversion of Control frameworks that paradigm applies to them as well. They control objects in your application. They instantiate them, manage their lifecycle, invoke methods on them, modify them, configure them, decorate them, do all sorts of stuff with them. The main point here is – the application is completely unaware of that. I feel tempted to put another Matrix analogy here, but hopefully you get the point without it.

The most visible manifestation of this fact, which clearly illustrates the lack of any knowledge about the container is that I tend not to reference the container in the application at all. The only place where the reference to the container does appear is the root project which only runs the application. It however contains no application logic and serves merely as application entry point and container bootstrapper.

Not referencing the container at all serves a few purposes. Most importantly it helps to enforce good OOP design, and blocks the temptation to take shortcuts and use the container as Service Locator.

Three calls pattern of usage

Now, probably the most interesting part is this simple bootstrapper. How do I interact with the container?

I tend to use pattern of three calls to the container. Yes you heard it right – I only call the container is three places in the entire application* (conditions apply, but I’ll discuss this below in just a moment).

My entire interaction with the container usually looks like this:

var container = BootstrapContainer();

finder = container.Resolve<IDuplicateFinder>();
var processor = container.Resolve<IArgumentsParser>();
Execute( args, processor, finder );

container.Dispose();

The three steps are:

  1. Bootstrap the container
  2. Resolve root components
  3. Dispose the container

Let’s go over them in turn:

One Install to rule them all…

Bootstrapping is incredibly simple:

private IWindsorContainer BootstrapContainer()
{
    return new WindsorContainer()
                  .Install( FromAssembly.This() );
}

The most important rule here (which is important in Windsor, but good to follow with other containers that enable this)  is – to call Install just once and register and configure all the components during this single call. Also important stuff is to use the Install method and Installers to encapsulate and partition registration and configuration logic. Most other containers have that capability as well. Autofac and Ninject call it modules, StructureMap calls it registries.

As you can see on the screenshot above I usually have a dedicated folder called Installers in my bootstrap assembly where I keep all my installers. I tend to partition the installers so that each one of them installs some cohesive and small set of services. So I might have ViewModelsInstaller, Controllers Installer, BackgroundServicesInstaller, LoggingInstaller etc. Each installer is simple and most of them look similar to this:

public class ArgumentInterpretersInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel));
        container.Register(
            Component.For<IArgumentsParser>()
                .ImplementedBy<ArgumentsParser>().LifeStyle.Transient,
            Component.For<IParseHelper>().ImplementedBy<ParseHelper>(),
            AllTypes.FromAssemblyContaining<IArgumentInterpreter>()
                 .BasedOn<IArgumentInterpreter>()
                 .WithService.Base());
    }
}

This partitioning helps keep things tidy, and by leveraging Installers you end up writing less code, as now Windsor will autodiscover them and register in just a single call to FromAssembly.This(). Also another noteworthy fact about this, is that you leverage Inversion of Control principle to configure the container itself. Instead of passing the container around, which should always raise a read flag, you’re telling Windsor – configure yourself. Nice and tidy.

Another important thing to notice, is that I tend to leverage convention based registration, rather than registering all the components one by one. This greatly cuts down the size of your registration code. It takes the burden of registering each newly added components manually off of your shoulders. It also enforces consistency in your code, because if you’re not consistent your components won’t get registered.

* yes – I do interact with the container in the installers, so I clearly break the three calls rule, right? No – I interact with the container in objects that extend, or modify the container itself – in this case it’s obviously not a bad thing.

…and in one Resolve bind them

Similar to unit tests principle – one logical assert per tests, I follow the rule of allowing explicit call to resolve in just one place in the entire application. Usually this will be just one call, that pulls the root component (Controller in MVC application, Shell in WPF application, or whatever the root object in your app is). In the example above I have two root objects so I have two calls to Resolve. That’s usually OK. However if you have more than three, you might want to take a closer look at reasons for that, as it’s quite unlikely you really need this.

The important thing is to have the Resolve calls in just this one single place and nowhere else in your application. Why that’s important? To fully leverage container’s potential, instead of telling it at every step what it should do. Let it spread its wings.

Clean up

It is important to let the container clean up after itself, when its done doing its job. In this case I can not only say that this is something I do. You also always should dispose your container at the end of your application. Always, no exceptions. This will let the container to shutdown gracefully, decommission all the components, give them chance to clean up after themselves, and free all the resources they may occupy.

 

What about you? How do you use your container?

On C# 4, co/contra-variance and generic constraints

While trying to clean up some code today, I stumbled upon interesting result of certain refactoring.

Given the following covariant interface and its implementation:

 

public interface IReference<out T> { }

public class ComponentReference<T> : IReference<T> { }

and the following usage:

public static IReference<IInterceptor> ForType<T>() where T : IInterceptor

{

    return new ComponentReference<T>();

}

the code won’t compile. However, not all is lost – if you cast explicitly, everything will work just fine:

public static IReference<IInterceptor> ForType<T>() where T : IInterceptor

{

    return (IReference<IInterceptor>)new ComponentReference<T>();

}

Castle Windsor and child containers: Revolutions

Continuing the topic from the previous posts.

What would happen?

Current behavior of Windsor is somewhat flawed. What it will do is it will resolve foo, and provide it with bar. The flaw of this behavior is that now when we resolve foo via any of the tree containers we’ll  get the same instance (since it’s a singleton). This introduced two issues:

  • component from childA (bar) will now be available via childB and parent while logically thinking – it should not.
  • we have temporal coupling in our code. Depending on the order of containers we’ll use to resolve foo we’ll get different results

So what should happen?

Ok, so now that we agreed that current behavior is indeed flawed (we did, didn’t we?) what are our options for fixing it? We basically have two options (both of which were mentioned in comments to previous post).

It all boils down to scoping. If we have a per-web-request object – should single instance be shared among multiple containers or should it be per-web-request-and-per-container? If we have singleton should it be single instance per container, per container hierarchy or per process?

Let’s consider slightly more complicated picture.

containers_2

Now we have two components for bar, one in childA and one in parent. Also we have one more component; baz, which is registered in childB.

classes_2

Baz has dependency on foo, foo still has dependency on bar. All of these dependencies are optional, and all components are singletons.

There can only be one

We want to scope instances strictly per their container. So that foo is scoped in parent (thus visible from its child containers as well), and bar is scoped per childA. This appears to be the simplest setup, and the most in line with definition of singleton, but then we run into problems outlined above.

We then could add another constraint – dependencies can only face upwards the container hierarchy. We would then get foo with its dependency on bar pulled from parent container, consistently, regardless of the container we’d resolve it from. Moreover, we could resolve baz from childB and its dependency would be properly populated from parent since it comes from a container that is higher in the hierarchy, so we’re safe to pull that dependency.

On the other hand this robs us of one of nice (and often used) side effect of child containers, that is contextual overriding of components from containers higher up the hierarchy.

If we have bar in childA, we’d expect to get foo pulled via childA to have that bar, not parent’s bar.

Or perhaps not?

We can approach the problem from another angle altogether. We can narrow down the scope of a component instance, to the scope of its outermost dependency. What do I mean by that?

When resolving foo from childA the outermost dependency of foo would be the bar living in childA. Therefore the instance of foo would have bar pulled from parent, but scoped in childA. Therefore when we’d request foo again, but this time from childB we’d get another instance of foo, with dependency on bar pulled from parent. This could potentially lead to problems as well, since if you’re depending on the fact that single instance of your component will ever live in the application at given point in time you may end up with problems.

So what do you think? Which approach would you prefer, or is there something I’m missing here?

To those who though I’m seriously going to remove support for nested containers rest assured this is not going to happen. I still think this could be a viable option and I wanted to throw it into the air, but its become such a core feature of each IoC container, that Windsor would look crippled if it didn’t have it, regardless of whether or not it’d be actually needed.

Castle Windsor and Child containers reloaded

This is a follow up to my previous post. I deliberately didn’t discuss the issues that arise when using container hierarchies to get some feedback on usage first.

So what’s the problem?

Consider trivial scenario:

two

We have two components, where foo depends on bar. The dependency is optional, which means that foo can be constructed even when bar is not available.

Then we have the following container hierarchy:

one

We have parent container where foo is registered and two child containers. In one of them we register bar. Both foo and bar are singletons (for sake of simplicity – the example would work for any non-transient lifestyle).

Now we do this

var fooA = childA.Resolve<Foo>();

var fooB = childB.Resolve<Foo>();

What should happen?

Castle Windsor and child containers

Neal started looking into behaviour of child containers in Windsor. This is an area that’s very rarely used, and as Hammett wrote two years ago – this is speaking with the devil himself. No one really ever uses it so it never got well defined and as Neal found out there are certain inconsistencies, and grey areas there.

This was a don’t ask, don’t tell area, and since Neil opened that can of worms, it’s time to deal with the issue. I’m considering several solutions, and the one I’m leaning towards most would be probably the most controversial.

Remove support for child containers altogether?

Basically handler selectors and sub-resolvers give you all the power you need to handle scenarios where you would want to use child container instead. I think removing the child containers, and add some nicer support for contextual scoping of components would be the best solution.

The point of this post however is to get your thoughts on this issue. Are you using child containers in Windsor? What are you using it for? How are you using it? Write a comment or if you don’t want to share that in public just drop me an email. I’d really like to get a clean picture of how usage of this feature looks like at this point in time, before I make a decision.

Contextual controller injection in ASP.NET MVC with Castle Windsor

I chatting the other day with Chris Canal, who played with reimplementing piece of code Jimmy Bogard put on his blog using Castle Windsor.

While I’m not an ASP.NET MVC expert by no means, I decided to give it a go and try to do it myself. See Jimmy’s post first to get the context, as I’m only going to talk about the code.

The code here uses development build of Windsor (what will become version 2.5) and does not work with version 2.1

No child container

Jimmy used child container to scope the contextual dependencies. While this is also possible using Windsor, it feels like using shotgun to kill a fly. We can use contextual meta-components that will have the sole purpose of scoping our RequestContext and ControllerContext and achieve the same effect as if we were using child container, only this is far more lightweight.

public class ControllerContextHost

{

    private ControllerBase controller;

 

    public void SetController( ControllerBase controller )

    {

        if( controller != null )

        {

            throw new InvalidOperationException( "Controller was already set!" );

        }

        this.controller = controller;

 

    }

 

    public ControllerContext GetContext()

    {

        if( controller == null )

        {

            return null;

        }

        return controller.ControllerContext;

    }

}

 

public class RequestContextHost

{

    private RequestContext context;

    public void SetContext( RequestContext context )

    {

        if( context != null )

        {

            throw new InvalidOperationException( "Context was already set!" );

        }

        this.context = context;

    }

    public RequestContext GetContext()

    {

        if( context == null )

        {

            throw new InvalidOperationException( "Context was not set!" );

        }

        return context;

    }

}

Having that we can now simply use the hosts to cache their respective components. We set the RequestContext in ControllerFactory.

public IController CreateController( RequestContext requestContext, string controllerName )

{

    var host = this.container.Resolve<RequestContextHost>();

    host.SetContext( requestContext );

    return container.Resolve<IController>( controllerName );

}

Registration

ControllerContext has a twist. Since we register controllers as transient, we have to pass the controller to ControllerContextHost right after it gets created. We use OnCreate method for that.

public void Install(IWindsorContainer container, IConfigurationStore store)

{

    container.Register(AllTypes.FromAssemblyContaining<HomeController>()

                            .BasedOn<IController>()

                            .Configure(x => x.LifeStyle.Transient

                                                    .Named(GetControllerName(x.Implementation))

                                                    .OnCreate((k, c) => k.Resolve<ControllerContextHost>()

                                                                            .SetController(c as ControllerBase))));

}

It is also important how we register the services:

public void Install( IWindsorContainer container, IConfigurationStore store )

{

    container.Register( Component.For<ControllerContextHost>().LifeStyle.PerWebRequest,

                        Component.For<RequestContextHost>().LifeStyle.PerWebRequest,

                        Component.For<RequestContext>()

                            .UsingFactoryMethod( k => k.Resolve<RequestContextHost>().GetContext() ),

                        Component.For<HttpContextBase>()

                            .UsingFactoryMethod( k => k.Resolve<RequestContext>().HttpContext ),

                        Component.For<Func<ControllerContext>>()

                            .UsingFactoryMethod<Func<ControllerContext>>(

                                k => k.Resolve<ControllerContextHost>().GetContext ) );

}

Both hosts are registered as per web request since that’s how we want to cache the contexts they host. We’re only going to use the hosts internally and not expose them. Hence we register the contexts via UsingFactoryMethod. We also don’t register the ControllerContext directly, but rather via Func delegate, to break cyclic dependency between ControllerContext and Controller.

Now we only need to register the remaining services we want to use:

public void Install( IWindsorContainer container, IConfigurationStore store )

{

    container.Register(

        Component.For<IFoo>().ImplementedBy<Foo>().LifeStyle.Transient,

        Component.For<IActionInvoker>().ImplementedBy<ControllerActionInvoker>().LifeStyle.Transient,

        Component.For<ITempDataProvider>().ImplementedBy<SessionStateTempDataProvider>().LifeStyle.Transient,

        Component.For<RouteCollection>().Instance( RouteTable.Routes ),

        Component.For<UrlHelper>().LifeStyle.Transient );

}

and we’re free to take dependency on IFoo, which has dependency on our contextual services. Just for completeness, here’s code registering all the components in the container:

this._windsorContainer = new WindsorContainer()

    .Install( FromAssembly.This() );

And now, assuming I didn’t mis-translate Jimmy’s StructureMap code, out application should work just like his sample.

Select is broken? (.NET 4)

Daniel pinged me today that he stumbled upon odd issue while trying to update Moq to use Castle DynamicProxy 2.2. I investigate a bit more and it appears to be one of these this-cannot-be-happening-select-is-broken situations.

When DynamicProxy tries to replicate an attribute on one method, its CustomAttributeData contains contradictory information. It happens only when running on .NET 4 (the method in question does not have the attribute in previous versions of BCL)

Select is broken

That’s the method in question in Reflector:

Reflector

Here’s simplified code sample that reproduces the issue:

var method = typeof(HtmlInputText).GetMethod("GetDesignModeState", BindingFlags.Instance | BindingFlags.NonPublic);

Debug.Assert(method != null, "method != null");

var attributes = CustomAttributeData.GetCustomAttributes(method);

Debug.Assert(attributes.Count == 1, "attributes.Length == 1");

var attribute = attributes[0];

Debug.Assert(attribute.Constructor.GetParameters().Length == attribute.ConstructorArguments.Count, "This fails");

 

Now – what am I missing? Is this really bug in BCL v4 or am I doing something wrong here?