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 property:

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 value of the prop­erty using a pri­vate set­ter 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 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­ately 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­erty defined in a class that’s going to be injected into your appli­ca­tion by Castle!

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; } }
}
Share
One of the more obscure things I have had to do inside a Cas­tle con­fig is to spec­ify an IEnumerable<T> instance which required tak­ing the tech­nique I showed in this post a lit­tle 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 spec­i­fied the lifestyle of this IEnumerable<T> to be sin­gle­ton as in most cases where you would want to do some­thing like this is to be able to con­fig­ure some­thing once and use it every­where, but you should change it to suit your needs.

Share

If you have an inter­face like this:

IDal<T>

with a con­crete class like this, which you want to wire up with Castle:

Dal : IDal<IEntity>

Then here’s the syn­tax to spec­ify the com­po­nent in your Cas­tle Wind­sor con­fig­u­ra­tion file

<component id="myDal"
           service="Namespace.IDal`1[[Namespace.IEntity, Assembly]], Assembly"
           type="Namespace.Dal, Assembly"/>

Sim­i­larly, imag­ine if you have more than one generic type parameter:

IRetrievable<T, idT>
FooRetriever : IRetrievable<Foo, string>
<component id="FooRetriever"
           service="Namespace.IRetrievable`2[[Namespace.Foo, Assembly],[System.String]], Assembly"
           type="Namespace.FooRetriever, Assembly"/>

Remem­ber, you need to use the back tick (), NOT apostrophes (‘)!

Ref­er­ences:

Stack­Over­flow ques­tion on the syn­tax to declare generic types in cas­tle config

Stack­Over­flow ques­tion on declar­ing more than one para­me­ter type in cas­tle config

Share

Def­i­n­i­tion:

Depen­dency Inver­sion Prin­ci­ple refers to a spe­cific form of decou­pling aimed at rend­ing high-level mod­ules inde­pen­dent of the low-level mod­ules’ imple­men­ta­tion details. Its prin­ci­ple states:

  • High-level mod­ules should not depend on low-level mod­ules, both should depend on abstractions.
  • Abstrac­tions should not depend upon details. Details should depend upon abstractions.

Depen­dency Inver­sion Prin­ci­ple is often talked about in con­nec­tion with Inver­sion of Con­trol or Depen­dency Injection.

Pur­pose:

Even in N-tiered appli­ca­tions you can often find tight cou­pling between the dif­fer­ent lay­ers, usu­ally from upper to lower lay­ers but not vice versa. For exam­ple, whilst your busi­ness layer might be inti­mately famil­iar with and depen­dent on your data access layer, the reverse is not true. This how­ever, still rep­re­sents a cou­pling prob­lem and it:

  • makes changes to the data access layer more dif­fi­cult as it might require changes to the busi­ness layer (rip­ple effect)
  • makes it hard to unit test the dif­fer­ent lay­ers in isolation

Depen­dency inver­sion (and decou­pling in gen­eral) allows soft­ware archi­tects to design their sys­tems with greater flex­i­bil­ity by loos­en­ing up the depen­den­cies between the dif­fer­ent lay­ers of their system.

Part­ing thoughts…

  • Cou­pling is like radi­a­tion, there are harm­less back­ground cou­pling every­where (say, the core .Net libraries!), but expo­sure to tight cou­pling across the ser­vice boundaries/between inter­con­nected mod­ules in your appli­ca­tion can be haz­ardous! With that said, with­out any cou­pling your sys­tem is as good as useless.
  • Tight cou­pling restricts a system’s abil­ity to change in an indus­try where the only con­stant is change!

Fur­ther reading:

Loosen Up – Tame Your Soft­ware Depen­den­cies For More Flex­i­ble Apps (MSDN arti­cle by James Kovac)

Robert C. Martin’s arti­cle on Depen­dency Inver­sion Principle

Design Pat­tern – Inver­sion of Con­trol and Depen­dency Injec­tion (by Shiv­prasad Koirala)

Share

Def­i­n­i­tion:

Inver­sion of Control (IoC) refers to the inver­sion of the flow of con­trol (the order in which indi­vid­ual state­ments, func­tion calls, etc. are exe­cuted) in a soft­ware. You’ll often hear the term Hol­ly­wood prin­ci­ple being men­tioned in the same breath as IoC, it sim­ply states “Don’t call us, we’ll call you” which more or less sums up the prin­ci­ples of IoC.

Pur­pose:

In tra­di­tional soft­ware design, the flow of con­trol is gov­erned by a cen­tral piece of code which often have to address mul­ti­ple con­cerns (log­ging, val­i­da­tion, etc.) and need to be aware of the imple­men­ta­tion details of its depen­den­cies. This cre­ates a very tightly cou­pled appli­ca­tion where changes in one com­po­nent have a rip­ple effect through­out the rest of the application.

Fol­low­ing the prin­ci­ples of IoC can help you achieve:

  • decou­pling of exe­cu­tion of a task from imple­men­ta­tion (through the use of interfaces)
  • greater sep­a­ra­tion of con­cerns (each com­po­nent only focuses on what it’s designed to do)
  • more flex­i­bil­ity (imple­men­ta­tion can be eas­ily changed with­out any side effects on other components)
  • more testable code (enables the use of stubs/mocks in place of con­crete classes intended for production)

Advan­tages:

  • Sim­pli­fies the build­ing of spe­cific tasks.

Dis­ad­van­tages:

  • Has the poten­tial to make the flow of con­trol in an appli­ca­tion more com­plex, and there­fore mak­ing it harder to follow.

Part­ing thoughts..

  • Mis­us­ing or abus­ing IoC can result in Mac­a­roni code.
  • IoC is not a sil­ver bul­let for all your sys­tem engi­neer­ing prob­lems, and remem­ber, “Don’t fix what’s not broken”
  • When adopt­ing IoC, there is addi­tional train­ing needs for new join­ers to the team.
  • Design sys­tems for flex­i­bil­ity, which allows quick adap­ta­tion to chang­ing environment/requirementsimage
  • Avoid com­pli­cat­ing sys­tem design by try­ing to be future-proof upfront, you can’t pre­dict the future! image

Fur­ther readings:

.NetRocks show 362 — James Kovac Inverts our Control!

Loosen Up — Tame Your Soft­ware Depen­den­cies For More Flex­i­ble Apps (MSDN arti­cle by James Kovac)

Design Pat­tern — Inver­sion of Con­trol and Depen­dency Injec­tion (by Shiv­prasad Koirala)

Share