Castle Windsor Tips – say NO to private setter

Now, this is something that has stung me and every single one of my colleagues time and time again..

Imagine you have an interface called IMyConfiguration which has a get-only property:

public interface IMyConfiguration
{
    int Port { get; }
}

And the implementing class takes in a parameter called port in the constructor and sets the value of the property using a private setter on the property:

public class MyConfiguration : IMyConfiguration
{
    public MyConfiguration(int port)
    {
        Port = port;
    }

    public int Port { get; private set; }
}

All looks fine, you set up your castle config to pass in an integer called port:

<component id="MyConfiguration"
           service="MyAssembly.IMyConfiguration, MyAssembly"
           type="MyAssembly.MyConfiguration, MyAssembly"
           lifestyle="singleton">
    <parameters>
        <port>1234</port>
    </parameters>
</component>

And you hit Run, and immediately you run into a Castle exception, the exception message is less than useful as it only says ”Object reference not set to an instance of an object.” and the stack trace (see below) doesn’t reveal anything useful either..

image

If this sounds familiar to you then you should make a note to self as I have done and remember to not use a private setter on a property defined in a class that’s going to be injected into your application by Castle!

To fix this error, you will need to change your implementation to something like this instead:

public class MyConfiguration : IMyConfiguration
{
    private readonly int _port;

    public MyConfiguration(int port)
    {
        _port = port;
    }

    public int Port { get { return _port; } }
}
  • http://kozmic.pl Krzysztof Ko?mic

    Perhaps you can elaborate on your scenario? I just reproduced it, and it works as advertised on Windsor 2.5 beta2.

  • theburningmonk

    Hi Krzysztof, that’s excellent news! I believe we’re still running v2.1, let me try to reproduce the same exception with v2.5 beta2 and update accordingly.