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

Castle Windsor Tips – specifying IEnumerable in config file

One of the more obscure things I have had to do inside a Castle config is to specify an IEnumerable<T> instance which required taking the technique I showed in this post a little further:
<component id="MyTypes"
           service="System.Collections.Generic.IEnumerable`1[[Type, Assembly]], mscorlib"
           type="System.Collections.Generic.List`1[[Type, Assembly]], mscorlib"
           lifestyle="singleton">
    <parameters>
        <collection>
            <array>
                <item>${Item1}</item>
                <item>${Item2}</item>
            </array>
        </collection>
    </parameters>
</component>

I specified the lifestyle of this IEnumerable<T> to be singleton as in most cases where you would want to do something like this is to be able to configure something once and use it everywhere, but you should change it to suit your needs.

Castle Windsor Tips – specifying generic types in config file

If you have an interface like this:

IDal<T>

with a concrete class like this, which you want to wire up with Castle:

Dal : IDal<IEntity>

Then here’s the syntax to specify the component in your Castle Windsor configuration file

<component id="myDal"
           service="Namespace.IDal`1&#91;&#91;Namespace.IEntity, Assembly&#93;&#93;, Assembly"
           type="Namespace.Dal, Assembly"/>

Similarly, imagine if you have more than one generic type parameter:

IRetrievable<T, idT>
FooRetriever : IRetrievable<Foo, string>
<component id="FooRetriever"
           service="Namespace.IRetrievable`2&#91;&#91;Namespace.Foo, Assembly&#93;,&#91;System.String&#93;&#93;, Assembly"
           type="Namespace.FooRetriever, Assembly"/>

Remember, you need to use the back tick (`), NOT apostrophes (‘)!

References:

StackOverflow question on the syntax to declare generic types in castle config

StackOverflow question on declaring more than one parameter type in castle config

Buzzword Buster – Dependency Inversion Principle

Definition:

Dependency Inversion Principle refers to a specific form of decoupling aimed at rending high-level modules independent of the low-level modules’ implementation details. Its principle states:

  • High-level modules should not depend on low-level modules, both should depend on abstractions.
  • Abstractions should not depend upon details. Details should depend upon abstractions.

Dependency Inversion Principle is often talked about in connection with Inversion of Control or Dependency Injection.

Purpose:

Even in N-tiered applications you can often find tight coupling between the different layers, usually from upper to lower layers but not vice versa. For example, whilst your business layer might be intimately familiar with and dependent on your data access layer, the reverse is not true. This however, still represents a coupling problem and it:

  • makes changes to the data access layer more difficult as it might require changes to the business layer (ripple effect)
  • makes it hard to unit test the different layers in isolation

Dependency inversion (and decoupling in general) allows software architects to design their systems with greater flexibility by loosening up the dependencies between the different layers of their system.

Parting thoughts…

  • Coupling is like radiation, there are harmless background coupling everywhere (say, the core .Net libraries!), but exposure to tight coupling across the service boundaries/between interconnected modules in your application can be hazardous! With that said, without any coupling your system is as good as useless.
  • Tight coupling restricts a system’s ability to change in an industry where the only constant is change!

Further reading:

Loosen Up – Tame Your Software Dependencies For More Flexible Apps (MSDN article by James Kovac)

Robert C. Martin’s article on Dependency Inversion Principle

Design Pattern – Inversion of Control and Dependency Injection (by Shivprasad Koirala)

Buzzword Buster – IoC

Definition:

Inversion of Control (IoC) refers to the inversion of the flow of control (the order in which individual statements, function calls, etc. are executed) in a software. You’ll often hear the term Hollywood principle being mentioned in the same breath as IoC, it simply states "Don’t call us, we’ll call you" which more or less sums up the principles of IoC.

Purpose:

In traditional software design, the flow of control is governed by a central piece of code which often have to address multiple concerns (logging, validation, etc.) and need to be aware of the implementation details of its dependencies. This creates a very tightly coupled application where changes in one component have a ripple effect throughout the rest of the application.

Following the principles of IoC can help you achieve:

  • decoupling of execution of a task from implementation (through the use of interfaces)
  • greater separation of concerns (each component only focuses on what it’s designed to do)
  • more flexibility (implementation can be easily changed without any side effects on other components)
  • more testable code (enables the use of stubs/mocks in place of concrete classes intended for production)

Advantages:

  • Simplifies the building of specific tasks.

Disadvantages:

  • Has the potential to make the flow of control in an application more complex, and therefore making it harder to follow.

Parting thoughts..

  • Misusing or abusing IoC can result in Macaroni code.
  • IoC is not a silver bullet for all your system engineering problems, and remember, "Don’t fix what’s not broken"
  • When adopting IoC, there is additional training needs for new joiners to the team.
  • Design systems for flexibility, which allows quick adaptation to changing environment/requirementsimage
  • Avoid complicating system design by trying to be future-proof upfront, you can’t predict the future! image

Further readings:

.NetRocks show 362 – James Kovac Inverts our Control!

Loosen Up – Tame Your Software Dependencies For More Flexible Apps (MSDN article by James Kovac)

Design Pattern – Inversion of Control and Dependency Injection (by Shivprasad Koirala)