Archive for the 'Windsor Castle' Category

Published by breki on 24 Aug 2010

Windsor Castle: Strange Resolving Behavior

A user reported a bug in Maperitive – it throws

Castle.MicroKernel.Resolvers.DependencyResolverException: Could not resolve non-optional dependency for ‘Karta.DataSources.OsmFileMapDataSource’ (Karta.DataSources.OsmFileMapDataSource). Parameter ‘fileName’ type ‘System.String’

I tried to reproduce this behavior using a simple unit test, but I couldn’t, so I’m posting the actual code. This is where the exception occurs:

return windsorContainer.Resolve<OsmFileMapDataSource>();

And this is how OsmFileMapDataSource constructors look like:

        public OsmFileMapDataSource(
            string fileName,
            IFileSystem fileSystem,
            IMapDataLayerFactory layerFactory)
        {
            ...
        }

        public OsmFileMapDataSource(IMapDataLayerFactory layerFactory)
        {
           ...
        }

Needless to say, both IFileSystem and IMapDataLayerFactory are registered in the container (IMapDataLayerFactory is registered as a typed factory, by the way). OsmFileMapDataSource is also registered as an implementation of itself. And I’m using version 2.1.0.6655 of the library.

What’s strange about this is that if I move the second constructor in front of the first one, the component is resolved without problems. I’m not sure if this is intended behavior, but I doubt the order of constructors should be a determining factor on how components are resolved.

But as I said, I couldn’t reproduce this behavior using a simplified test code, so I guess I should start debugging it instead.

Published by breki on 11 Jul 2010

Windsor Castle: Auto-Wiring Using Parameter Names

NOTE: this is probably only one way of doing things in Windsor Castle. If you know of any other, don’t hesitate to write a comment.

A design problem I was trying to solve yesterday: I have a component which depends on two implementations of the same interface:

public class HelpCommand (    
   ICommandDescriptor oneLinerDescriptor,     
   ICommandDescriptor detailedDescriptor)     
{     
   ...     
}     

HelpCommand prints out human-readable descriptions of various commands in Maperitive. If the user specifies the exact command, HelpCommand prints out a detailed description. On the other hand, if the command parameter is not specified, HelpCommand lists all of the commands and prints a one-liner description for each of them. So there are two implementations of the ICommandDescriptor interface: OneLinerDescriptor and DetailedDescriptor classes.

The problem I was having with this design is that all of my *Command components are registered in one go, using the convention like

container.Register (AllTypes.Of<ICommand>().FromAssembly (typeof(ICommand).Assembly)    
   .Configure (c => c.Named (c.Implementation.Name).LifeStyle.Transient));

so I’m letting Windsor do all the wiring magic without me being able to provide any custom registration logic for individual commands like HelpCommand. So how do I tell Windsor which component to use for oneLinerDescriptor and which for detailedDescriptor?

Bad Solution

Of course, I could simply specify the concrete implementations in HelpCommand’s constructor:

public class HelpCommand (    
   OneLinerDescriptor oneLinerDescriptor,     
   DetailedDescriptor detailedDescriptor)     
{     
   ...     
}     

But this couples the three classes together and goes against the “rely on abstractions, not implementations” mantra. It also makes unit testing of HelpCommand more difficult, since I have to drag the two descriptor classes around (and they could have their own dependencies to satisfy, which further bloats the unit testing code).

Factories?

I could use a factory to get the implementations I need, but that would be wasteful: a simple constructor dependency is much slicker and it doesn’t introduce an additional component (factory) into the picture. Also, factories are more suited for components which are created later, on-demand. In my case I want the descriptors to be available right at the beginning of HelpCommand’s lifecycle.

Resolving By Name

So I got an idea: why not use the name of the constructor parameter as an indicator of what kind of implementation I need?

This requires writing a custom subresolver:

    public class SubDependencyResolverByName : ISubDependencyResolver
    {
        public SubDependencyResolverByName(IKernel kernel, string componentPrefix)
        {
            this.kernel = kernel;
            this.componentPrefix = componentPrefix;
        }

        public bool CanResolve(
            CreationContext context, 
            ISubDependencyResolver contextHandlerResolver, 
            ComponentModel model, 
            DependencyModel dependency)
        {
            if (dependency.IsOptional)
                return false;

            return FindCandidateComponent(dependency.DependencyKey, dependency.TargetType) != null;
        }

        public object Resolve(
            CreationContext context, 
            ISubDependencyResolver contextHandlerResolver, 
            ComponentModel model, 
            DependencyModel dependency)
        {
            ComponentModel dependencyResolvingComponent = FindCandidateComponent (dependency.DependencyKey, dependency.TargetType);
            return kernel.Resolve(dependencyResolvingComponent.Name, dependency.TargetType);
        }

        protected ComponentModel FindCandidateComponent (string dependencyKey, Type targetType)
        {
            foreach (GraphNode node in kernel.GraphNodes)
            {
                ComponentModel visitedComponent = (ComponentModel) node;
                if (visitedComponent.Service != targetType)
                    continue;

                if (componentPrefix == null)
                {
                    if (0 == string.Compare(visitedComponent.Name, dependencyKey, StringComparison.InvariantCultureIgnoreCase))
                        return visitedComponent;
                }
                else
                {
                    if (false == visitedComponent.Name.StartsWith(componentPrefix, StringComparison.InvariantCultureIgnoreCase))
                        continue;

                    string nameWithoutPrefix = visitedComponent.Name.Substring(componentPrefix.Length);
                    if (0 == string.Compare (nameWithoutPrefix, dependencyKey, StringComparison.InvariantCultureIgnoreCase))
                        return visitedComponent;                    
                }
            }

            return null;
        }

        private readonly IKernel kernel;
        private readonly string componentPrefix;
    }

…and attaching it to the container:

container.Kernel.Resolver.AddSubResolver (
   new SubDependencyResolverByName (container.Kernel, "auto_"));

Results

Initially I had problems with this new resolver: it tried to be too smart and it messed with the existing (non-problematic) component wiring. So I decided to limit its scope only on dependency components which have a container ID starting with a certain prefix (in my case “auto_”). So if I want OneLinerDescriptor and DetailedDescriptor to be auto-detected by the resolver, I need to register them as “auto_OneLinerDescriptor” and “auto_DetailedDescriptor” in the Windsor container (casing is ignored). The resolver is currently limited to constructor dependencies only, but I see no reason it shouldn’t work for property injections too.

Is name-matching a good approach to auto-wiring components? I don’t know, time will tell. I certainly feel there’s something missing in how Windsor resolves dependencies by the default: type-matching is fine for simple scenarios, but as soon as you have more than one implementation of the same service interface, you need to specify service overrides or rely on "black magic” to wire things for you.

Published by breki on 05 Mar 2010

Disposing Of The Evidence

Garbage?
Creative Commons License photo credit: wok

In the previous post we discussed various relationships between singletons and transients in an inversion of control container. I introduced WindsorContainerInspector, a little utility class for analyzing the container and showed a sample unit test which looks for singletons that rely on transient objects.

Now I’ll show a few other checks that I think are good to perform on the container. They involve disposability of objects.

Disposable Transients

Let’s say we have a transient service IWebClient:

public interface IWebClient : IDisposable
{
void DownloadMeSomething(string somethingUrl);
}

As you can see, the service implements IDisposable. Now let’s say we have a class DownloadData which depends on this service:

public class DownloadData
{
public DownloadData (IWebClient webClient) {...}

...
}

Note the constructor dependency on IWebClient. What’s wrong with this picture?

What happens when the DownloadData is no longer used? The webClient is not disposed. We could hold up some valuable system resource by not disposing of such an object. And since we know IWebClient is defined as transient in our IoC container, we can be pretty sure that DownloadData is the only one using the received IWebClient instance. So we are responsible for this instance!

In other words, our DownloadData should also be disposable. We can say that, in general, components that depend on disposable transients should also be disposable:

[Test, MultipleAsserts]
public void TransientsThatRelyOnDisposableTransientsShouldAlsoBeDisposable ()
{
    Type disposableType = typeof(IDisposable);
 
    IList<KeyValuePair<ComponentModel, ComponentModel>> dependencies = inspector.FindDependencies (
        (a, b) =>
        {
            return a.LifestyleType == LifestyleType.Transient && false == disposableType.IsAssignableFrom (a.Implementation)
                && b.LifestyleType == LifestyleType.Transient && disposableType.IsAssignableFrom(b.Service);
        });
 
    foreach (KeyValuePair<ComponentModel, ComponentModel> dependency in dependencies)
    {
        Assert.Fail (
            "Transient component {0} relies on the disposable transient component {1}, but it itself is not disposable",
            dependency.Key.Implementation.FullName,
            dependency.Value.Implementation.FullName);
    }
}

Some might say that this kind of check can be done by static analysis like FxCop. FxCop will detect this only if DownloadData stores the IWebClient in a class field. But we could have used IWebClient parameter just within the constructor and then forget about it:

public class DownloadData
{
public DownloadData (IWebClient webClient)
{
webClient.CheckConnection();
}
}

In such cases no warning will be issued by FxCop.

Disposable Implementations Of Non-Disposable Services

What if we had another service, called IMailChecker:

public interface IMailChecker
{
bool AnyNewMail();
}

and we implemented a GMailChecker:

public class GMailChecker : IMailChecker, IDisposable
{
public bool AnyNewMail() {...}
public void Dispose() {...}
}

Notice GMailChecker implements IDisposable in addition to IMailChecker interface. But IMailChecker itself is not defined as disposable. How will the user of IMailChecker service know whether the object it holds should be disposed or not?

One way would be to use reflection to determine this. But this is very cumbersome and easy to forget when coding. My way of thinking is that if there’s reasonable possibility the implementations of the service will require disposability, you should declare the service interface as disposable. We can check for this condition with the following unit test:

[Test, MultipleAsserts]
public void TransientsThatRelyOnDisposableTransientsShouldAlsoBeDisposable ()
{
    Type disposableType = typeof(IDisposable);
 
    IList<KeyValuePair<ComponentModel, ComponentModel>> dependencies = inspector.FindDependencies (
        (a, b) =>
        {
            return a.LifestyleType == LifestyleType.Transient && false == disposableType.IsAssignableFrom (a.Implementation)
                && b.LifestyleType == LifestyleType.Transient && disposableType.IsAssignableFrom(b.Service);
        });
 
    foreach (KeyValuePair<ComponentModel, ComponentModel> dependency in dependencies)
    {
        Assert.Fail (
            "Transient component {0} relies on the disposable transient component {1}, but it itself is not disposable",
            dependency.Key.Implementation.FullName,
            dependency.Value.Implementation.FullName);
    }
}

Below is the updated the implementation of WindsorContainerInspector. Next time we will be discussing issues (= mostly problems) around disposing stuff received from the Windsor container.

public class WindsorContainerInspector
{
    public WindsorContainerInspector(IWindsorContainer container)
    {
        this.container = container;
    }
 
    public IList<KeyValuePair<ComponentModel, ComponentModel>> FindDependencies(
        Func<ComponentModel, ComponentModel, bool> dependencyPredicate)
    {
        List<KeyValuePair<ComponentModel, ComponentModel>> dependencies = new List<KeyValuePair<ComponentModel, ComponentModel>>();
 
        foreach (GraphNode node in container.Kernel.GraphNodes)
        {
            ComponentModel dependingNode = (ComponentModel) node;
 
            foreach (GraphNode depender in node.Dependents)
            {
                ComponentModel dependerNode = (ComponentModel)depender;
 
                if (dependencyPredicate(dependingNode, dependerNode))
                    dependencies.Add(new KeyValuePair<ComponentModel, ComponentModel>(dependingNode, dependerNode));
            }
        }
 
        return dependencies;
    }
 
    public IList<ComponentModel> FindComponents (Func<ComponentModel, bool> predicate)
    {
        List<ComponentModel> components = new List<ComponentModel>();
 
        foreach (GraphNode node in container.Kernel.GraphNodes)
        {
            ComponentModel component = (ComponentModel) node;
            if (predicate(component))
                components.Add(component);
        }
 
        return components;
    }
 
    private readonly IWindsorContainer container;
}

Published by breki on 01 Mar 2010

The Delicate Dance Of Transience

H2O
Creative Commons License photo credit: Flowery Luza*

I’m in the final stages of polishing Maperitive before the first release. Well, not really polishing, I have a bunch of tasks yet to do, but I think I can see the light at the end of the tunnel.

As #I stated a while back#, one of the reasons I decided to do a major rewrite of the Kosmos code was to introduce inversion of control (IoC) into the architecture. Maperitive (ex-Kosmos) now heavily relies on Windsor Castle do to the wiring. I can say that investing in IoC (and sticking to SOLIDs) now starts to pay dividends: I can add new features with more ease and they tend to affect a relatively minor part of “old” code.

The problem with using IoC containers like Windsor Castle is when the components registered exceed a certain number that you can handle in your brain (Maperitive currently has about 130 components in IoC container). Then the whole thing gets a life of its own: even if you write extensive unit tests for individual parts, it gets more and more difficult to predict how the “organism” will behave as a whole.

When used in a Windows desktop application like Maperitive, the problem gets compounded by the intricate dependencies between different lifestyles of components. This is what I want to discuss in this post.

I’ll restrict the discussion to singletons and transients, since I only use these two types in Maperitive. I’ll give examples of components in terms of a mapping application (which Maperitive is), but I think it won’t be a problem to translate this to your own areas. I’ll start with the simple case of…

Singletons Depending On Singletons

This is the easy one: singletons are components which typically share the same lifespan as the application. A Map is a good example of a singleton: the user expects the map to be available at all times (after all, what would Google Earth look like without the map?). User typically uses a mouse to move around the map. And we luckily have only one mouse on our machines, so this is an example of another singleton (I’m a bit oversimplifying the stuff here, bear with me). So the Map subscribes to the Mouse events and this can be seen as singleton to singleton dependency.

These kind of dependencies are easy to handle, since the number of created objects is typically small and they all share the same lifespan. Also, singletons are (typically) created automatically by the IoC container at the start of the application so you don’t really need to explicitly create and destroy them yourself.

Transients Depending On Singletons

This is the second common relationship in a desktop application. You have a short-term task to do (usually as a response to user’s actions) and you create a transient object to do this task. One example would be a WebClient which downloads the map data from the server: once the download is done, you can kill the client (hmmm that sounds tempting).

Transients are typically created using factories. Windsor Castle offers a cool feature called TypedFactoryFacility which makes creating factories a lot easier (you don’t need to write the actual creation code, just specify your factory interface according to facility’s conventions).

A WebClient needs to know whether it has to provide credentials for the Web proxy. We can store this information in a Configuration object, which in our case is a singleton.

A transient component states its dependency on a singleton through constructor or property injection. Again, this scenario should be easy to handle, since the transient object has a shorter lifespan than the singleton it depends upon.

Transients Depending On Transients

This is where things can get messy. There are two possible scenarios when a transient object needs another transient object:

  1. They both share the same lifespan. Let’s say our WebClient wants to check if internet connection is up before sending a request to the download server. It can use a Ping service to ping google.com (it’s immoral, I know). Since both WebClient and Ping will be used for a short time, you can inject the Ping dependency in WebClient’s constructor. When WebClient dies, Ping should also die.
  2. The lifespans overlap, but are not the same.  Example: out WebClient has detected a communication problem with the download server and sends a notice to the user. The notice is displayed as a modeless dialog, which can stay on the screen until the user clicks on the Close button. So Notice is a transient object which does not die together with its creator, WebClient: once WebClient notifies the user, it is no longer needed. Notice, however, will live on until the user chooses to close it.

In the second case, having the Notice dependency in WebClient’s constructor or property is not an ideal option, for two reasons:

  1. It is not guaranteed the notice will even be used: if the download went OK, there is no need to notify the user. If your Notice component is expensive to create, this could be an issue.
  2. By using a constructor injection for a transient component, you are effectively claiming the ownership of this component. This conflicts with the fact that the component will live on even after your main component dies.

How do you solve this problem? My suggestion is to use factories – factories are usually singleton objects, so you end up with “transient depending on singleton” case. Even better: Windsor Castle’s TypedFactoryFacility also offers a mechanism to release components created with such factory.

The last (and most problematic) case is…

Singletons Depending On Transients

The problem with this is that your supposedly transient object will live the whole duration of the application lifetime. While in some cases this could be a valid scenario, in lot of cases it’s merely an oversight of the developer (especially when confronted with a huge number of components in a system).

Windsor Castle Inspector

The solution I used in Maperitive is to write a unit test which checks for singleton-to-transient relationships in my container and fails if it finds any:

[Test]
public void SingletonsShouldNotRelyOnTransients()
{
    IWindsorContainer container = Program.CreateWindsorContainer(false);
 
    WindsorContainerInspector inspector = new WindsorContainerInspector(
        container);
    IList<KeyValuePair<ComponentModel, ComponentModel>> dependencies 
         = inspector.FindDependencies(
        (a, b) =>
            {
                return (a.LifestyleType == LifestyleType.Singleton 
                    || a.LifestyleType == LifestyleType.Undefined)
                    && b.LifestyleType == LifestyleType.Transient;
            });
 
    Assert.AreEqual(0, dependencies.Count);
}

Of course, the condition for the test failure could be a bit modified to exclude any “special cases".

The code uses the WindsorContainerInspector, a little utility class I wrote to assist in inspecting the container:

public class WindsorContainerInspector
{
    public WindsorContainerInspector(IWindsorContainer container)
    {
        this.container = container;
    }
 
    public IList<KeyValuePair<ComponentModel, ComponentModel>> FindDependencies(
        Func<ComponentModel, ComponentModel, bool> dependencyPredicate)
    {
        List<KeyValuePair<ComponentModel, ComponentModel>> dependencies 
            = new List<KeyValuePair<ComponentModel, ComponentModel>>();
 
        foreach (GraphNode node in container.Kernel.GraphNodes)
        {
            ComponentModel dependingNode = (ComponentModel) node;
 
            foreach (GraphNode depender in node.Dependents)
            {
                ComponentModel dependerNode = (ComponentModel)depender;
 
                if (dependencyPredicate(dependingNode, dependerNode))
                    dependencies.Add(new KeyValuePair<ComponentModel, ComponentModel>(
                        dependingNode, 
                        dependerNode));
            }
        }
 
        return dependencies;
    }
 
    private readonly IWindsorContainer container;
}

Right now WindsorContainerInspector offers only one method: FindDependencies, which looks for dependencies based on the supplied predicate. I already have some additional ideas on what other possible problems to detect in the container, but I’lll write about this next time.