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; } }
}
Liked this article? Support me on Patreon and get direct help from me via a private Slack channel or 1-2-1 mentoring.
Subscribe to my newsletter


Hi, I’m Yan. I’m an AWS Serverless Hero and the author of Production-Ready Serverless.

I specialise in rapidly transitioning teams to serverless and building production-ready services on AWS.

Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.

Hire me.


Check out my new course, Complete Guide to AWS Step Functions. In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. Including basic concepts, HTTP and event triggers, activities, callbacks, nested workflows, design patterns and best practices.

Get Your Copy