Posted by & filed under .Net.

Welcome to part 1… today we’re looking at supporting basic configuration in components without additional coding by using the windsor container.

So – with the container we can provide configuration for a component which is loaded at runtime, so every time you start your app it will be read in – you can do this using the configuration support in .Net – but using castle makes support for this very code-light in comparison… let’s take a look.

So first off, we have a class we can use to calculate the tax on a gross ammount:

public class TaxCalculator
{
    private decimal _rate = 0.125m;
 
    public decimal Rate
    {
        set { _rate = value; }
        get { return _rate; }
    }
 
    public decimal CalculateTax(decimal gross)
    {
        return Math.Round(_rate*gross, 2);
    }
}

By default the tax rate is 12.5% – but we can change the tax rate by setting the “Rate” property.

Now, lets look at setting up the container… so we have this code in our sample:

private static void Main(string[] args)
{
    WindsorContainer container = new WindsorContainer(new XmlInterpreter());
 
    TaxCalculator calculator = container.Resolve();
 
    decimal gross = 100;
    decimal tax = calculator.CalculateTax(gross);
 
    Console.WriteLine("Gross: {0}, Tax: {1}", gross, tax);
    Console.Read();
}

The windsor container is constructed with an “XmlInterpreter” – this configuration will pull the setup for our container from a section in the App.config.

Let’s have a look at that:


 
  
    

Running the program will display: Gross: 100, Tax: 12.50

Now, what about changing the tax rate in the configuration?


 
  
    
0.25

Now running the program will display: Gross: 100, Tax: 25.00

And that’s part 1 done – so now you can see how can we supply configuration parameters, and provide sensible defaults for them.

Next time we’ll look at configuring arrays…

Comments are closed.