Previous posts in the series:
In tutorial #7, Alex shows us the real meat of DI, which is switching out implementations. This is where I had my “A-HA!” moment with Windsor and where I continue to see the most obvious value.
As Alex states, when switching implementations, you take the contract of your implementation and stuff it in an interface. Here’s the interface for our example:
public interface IMessageOfTheDay
{
string GetMessageOfTheDay();
}
And the same two implementations from Alex:
public class StaticMessageOfTheDay:IMessageOfTheDay
{
private string _message;
public string Message
{
set { _message = value; }
}
public string GetMessageOfTheDay()
{
return _message;
}
}
And #2:
public class WikiQuotesMessageOfTheDay : IMessageOfTheDay
{
public string GetMessageOfTheDay()
{
WebClient client = new WebClient();
string content = client.DownloadString(“http://en.wikiquote.org/wiki/Main_Page”);
string toFind = “<td align=\”center\”>”;
int start = content.IndexOf(toFind) + toFind.Length + 56;
int length = content.IndexOf(“<a”, start) – start;
return content.Substring(start, length);
}
}
(I had to change the string that Alex was searching on and hardcode a length to the beginning of the quote, so maybe I’ll rename this class to HorrificQuoteOfTheDay or something)
So, let us get to the Binsor config. First off, I put my interface in a separate namespace, so I had to add an import clause to the top of the Windsor.boo file. Then, I add the StaticMessageOfTheDay component:
import BitterCoder.Tutorials.Binsor.Core.Interfaces
component “motd.service”,IMessageOfTheDay,StaticMessageOfTheDay:
message=”Welcome to my Binsor tutorials”
Now, when I run the project, I get:
MOTD: Welcome to my Binsor tutorials
Changing out the motd.service component for the Wiki Quotes:
component “motd.service”,IMessageOfTheDay,WikiQuotesMessageOfTheDay
The running program now gives:
MOTD: Those works of art which have scooped up the truth and presented it to us
as a living force â?” they take hold of us, compel us, and nobody ever, not even
in ages to come, will appear to refute them. ~
It’s just that easy. Our quote is from Aleksandr Solzhenitsyn, whom I can safely say I’ve never heard of before, but I will take as a sign that this blog post is a work of art.
Next time, switching implementations by id….