Posted by & filed under .Net.


Switching lifestyles is the theme of this post… so what’s that
all about?

Well first off – what is a lifestyle, in basic terms it specifies how many instances will be available at any one time from the container – so at the one extreme we have components with a transient lifestyle, where any requests from those components will return new instances – and at the opposite end of the spectrum we have singleton components, where there is only one instance for the whole container – there are other types of lifestyle, but we’ll leave those for another post.

So first off – castle is all about convention over configuration, and by convention a component in the container is a singleton… so in this example we’ll look into ways in which you can switch a components lifestyle to being transient.

First off, heres our component:

public class AddingService
{
    private int _total = 0;
 
    public void AddAmmount(int ammount)
    {
        _total += ammount;
    }
 
    public int Total
    {
        get { return _total; }
    }
}

It lets us add stuff… how neat is that… lets see our program:

private static void Main(string[] args)
{
    WindsorContainer container = new WindsorContainer(new XmlInterpreter());
 
    AddingService sheepCounted = container.Resolve();
    AddingService catsHerded = container.Resolve();
 
    sheepCounted.AddAmmount(10);
    sheepCounted.AddAmmount(50);
 
    catsHerded.AddAmmount(3);
    catsHerded.AddAmmount(12);
 
    Console.WriteLine("You have counted {0} sheep and herded {1} angry cats", sheepCounted.Total,
                      catsHerded.Total);
 
    Console.Read();
}

And if we run it:

You have counted 75 sheep and herded 75 angry cats

That doesn’t seem right – our service is retaining a count, so we want a fresh instance of the class every time we request it – which means we should shift our component to the “transient” lifestyle – lets have a go at doing it with configuration, by adding the lifestyle attribute to the components definition.


 
  
    

And now if we run it again:

You have counted 60 sheep and herded 15 angry cats

That looks a bit better… but I propose that in many cases when your writing a component you know what it’s lifestyle should be, before it’s ever registered in a container – for instance in this case this class should always be transient, so we can actually decorate the class with a “Transient” attribute and can skip having to put the lifestyle in the configuration, this is how that would look:

[Transient]
public class AddingService
{
    private int _total = 0;
 
    public void AddAmmount(int ammount)
    {
        _total += ammount;
    }
 
    public int Total
    {
        get { return _total; }
    }
}

There are other lifestyles available to use – it’s worth having a look through the castle wiki for more details… and we’ll probably cover them in another post.

In the next part we will cover switching out implementations of components themselves.