Castle Windsor Tips – say NO to private setter

Yan Cui

I help clients go faster for less using serverless technologies.

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; } }
}

 

Whenever you’re ready, here are 4 ways I can help you:

  1. If you want a one-stop shop to help you quickly level up your serverless skills, you should check out my Production-Ready Serverless workshop. Over 20 AWS Heroes & Community Builders have passed through this workshop, plus 1000+ students from the likes of AWS, LEGO, Booking, HBO and Siemens.
  2. If you want to learn how to test serverless applications without all the pain and hassle, you should check out my latest course, Testing Serverless Architectures.
  3. If you’re a manager or founder and want to help your team move faster and build better software, then check out my consulting services.
  4. If you just want to hang out, talk serverless, or ask for help, then you should join my FREE Community.

 


2 thoughts on “Castle Windsor Tips – say NO to private setter”

  1. 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.

Leave a Comment

Your email address will not be published. Required fields are marked *