The Bitter Coder Tutorials, Binsor Style: Part IX, Constructor Injection

Thu, Aug 21, 2008 2-minute read

Previous posts in the series:

Part 9 of the original series focuses in on Constructor Injection, which is one method of doing Dependency Injection (the other is Setter Injection, which we’ll get to)   The reason to use Constructor or Setter Injection is a bit subjective, but (to me) boils down to if you the paramters to be mandatory and how many parameters you have.  We’re not here to debate, though, we’re here to copy Alex’s hard work….

Here’s the interface Alex defines;

public interface IEncoder

{

string Encode(string source);

}

And the two encoders:

public class NullEncoder:IEncoder

{

public string Encode(string source)

{

return source;

}

}

public class SillyEncoder:IEncoder

{

private char[] _mixedUp = “YACBDFEGIHJLKMONPRSQTUWVXZ”.ToCharArray();

public string Encode(string source)

{

string upperSource = source.ToUpper();

char[] encoded = new char[source.Length];

for (int i = 0; i < encoded.Length; i++)

{

encoded[i] = MapCharacter(upperSource[i]);

}

return new string(encoded);

}

private char MapCharacter(char ch)

{

if ((ch >= ‘A’) && (ch <= ‘Z’))

{

return _mixedUp[ch - ‘A’];

}

return ch;

}

}

Let’s check out the binsor:

component “null.encoder”, IEncoder, NullEncoder

component “silly.encoder”, IEncoder, SillyEncoder

component “message.sender”, SecretMessageSender:

_from=“ruprict@wordpress.com”

Notice we didn’t specify a value for the “_encoder” parameter, so Windsor will just plug in the first one it finds.  And, finally, the Program:

private static void Main(string[] args)

{

var sender = container.Resolve<SecretMessageSender>();

sender.SendMessage(“hammett”,“Howzit going at Microsoft?”);

}

Running this as is, gives us:

to: hammett from: ruprict@wordpress.com

GOWZIQ EOIME YQ KICROSOFQ?

So, what if we want to send an unencrypted message?  Well, we can specify which IEncoder component to wire to our sender, like so:

component “message.sender”, SecretMessageSender:

_from=“ruprict@wordpress.com”

_encoder=@null.encoder

See?  We refer to it by the name we gave the component.  Running it now, gives us:

to: hammett from: ruprict@wordpress.com

Howzit going at Microsoft?

(I bet he’s doing great…)

Setter injection…coming up!