The Bitter Coder Tutorials VIII: Referencing Instances By Key

Mon, Aug 18, 2008 2-minute read

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:

FileName=“file1.txt”

component “file2.reader”, FileReader:

FileName=“file2.txt”

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…