The Bitter Coder Tutorials VIII: Referencing Instances By Key

Previous posts in the series:

In tutorial #8, Alex continues down his path of switching implementations around, but this time we are going to have multiple components that implement the same contract, and we’ll specify which one we want by id.  The id we are talking about is the id we gave the component when we registered it with Windsor.  Enough blah, blah, onto the code.

Here’s our class to read a file:

public class FileReader


public string FileName { get; set; }

public string ReadToEnd()


return File.ReadAllText(FileName);



Now, we’ll register two components with the container, each one reading a different file.

component “file1.reader”, FileReader:


component “file2.reader”, FileReader:


Finally, the program code:

static void Main(string[] args)


FileReader defaultReader = container.Resolve<FileReader>();

FileReader file1Reader = container.Resolve<FileReader>(“reader.file1”);

FileReader file2Reader = container.Resolve<FileReader>(“reader.file2”);

Console.WriteLine(“Default contents: {0}”, defaultReader.ReadToEnd());

Console.WriteLine(“File1 contents: {0}”, file1Reader.ReadToEnd());

Console.WriteLine(“File2 contents: {0}”, file2Reader.ReadToEnd());


Adding the text files and running this bad boy gives the output:

Default contents: This is the contents of file 1
File1 contents: This is the contents of file 1.
File2 contents: This is the contents of file 2.

So, as Alex says, the default implementation is the first one in the file, just like using XML.

In his tutorial, Alex gives another example of why you would need to reference implementations by id, so if you’re interested, you can read it there (although, you shoulda already read that post…right?)

Next time, constructor injection…


About Ruprict

I am a nerd that is a Nerd Wannabe. I have more kids than should be allowed by law, a lovely wife, and a different sense of humor than most. I work in the field of GIS, where I am still trying to find myself on the map. View all posts by Ruprict

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: