Castle Windsor Tips — say NO to private setter

Now, this is some­thing that has stung me and every sin­gle one of my col­leagues time and time again..

Imag­ine you have an inter­face called IMy­Con­fig­u­ra­tion which has a get-only prop­er­ty:

public interface IMyConfiguration
{
    int Port { get; }
}

And the imple­ment­ing class takes in a para­me­ter called port in the con­struc­tor and sets the val­ue of the prop­er­ty using a pri­vate set­ter on the prop­er­ty:

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

    public int Port { get; private set; }
}

All looks fine, you set up your cas­tle con­fig to pass in an inte­ger 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 imme­di­ate­ly you run into a Cas­tle excep­tion, the excep­tion mes­sage is less than use­ful as it only says ”Object ref­er­ence not set to an instance of an object.” and the stack trace (see below) doesn’t reveal any­thing use­ful either..

image

If this sounds famil­iar to you then you should make a note to self as I have done and remem­ber to not use a pri­vate set­ter on a prop­er­ty defined in a class that’s going to be inject­ed into your appli­ca­tion by Cas­tle!

To fix this error, you will need to change your imple­men­ta­tion to some­thing like this instead:

public class MyConfiguration : IMyConfiguration
{
    private readonly int _port;

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

    public int Port { get { return _port; } }
}