I am trying to get started with Castle.Windsor and following a comment I made on the samples currently available for newbies (http://stw.castleproject.org/Windsor.Silvertlight_Sample_App_Customer_contact_manager.ashx?Discuss=1), I thought I’d take the bull by the horns and update the example provided here http://dotnetslackers.com/articles/designpatterns/InversionOfControlAndDependencyInjectionWithCastleWindsorContainerPart1.aspx.
This is a simple and fairly straightforward console application making use of Castle Windsor, albeit an outdated version. My Main method in Program.cs is as follows:
public static void Main()
{
IWindsorContainer container = new WindsorContainer();
container.Install(FromAssembly.This());
var retriever = container.Resolve<IHtmlTitleRetriever>();
Console.WriteLine(retriever.GetTitle(new Uri(ConfigurationManager.AppSettings["fileUri"])));
Console.Read();
container.Dispose();
}
and the Service and Components, which are all in the same file i.e. Program.cs are thus:
public interface IHtmlTitleRetriever
{
string GetTitle(Uri file);
}
public interface IFileDownloader
{
string Download(Uri file);
}
public interface ITitleScraper
{
string Scrape(string fileContents);
}
public class HtmlTitleRetriever: IHtmlTitleRetriever
{
private readonly IFileDownloader _downloader;
private readonly ITitleScraper _scraper;
public HtmlTitleRetriever(IFileDownloader dowloader, ITitleScraper scraper)
{
_downloader = dowloader;
_scraper = scraper;
}
public string GetTitle(Uri file)
{
string fileContents = _downloader.Download(file);
return _scraper.Scrape(fileContents);
}
}
public class HttpFileDownloader : IFileDownloader
{
public string Download(Uri file)
{
return new WebClient().DownloadString(file);
}
}
public class StringParsingTitleScraper : ITitleScraper
{
public string Scrape(string fileContents)
{
string title = string.Empty;
int openingTagIndex = fileContents.IndexOf("<title>");
int closingTagIndex = fileContents.IndexOf("</title>");
if(openingTagIndex != -1 && closingTagIndex != -1)
title = fileContents.Substring(openingTagIndex, closingTagIndex - openingTagIndex).Substring(7);
return title;
}
}
It is pretty much a straight copy of what Simone Busoli has from his example. The code compiles fine but I get the following error when I run the application:
No component for supporting the service WindsorSample.IHtmlTitleRetriever was found
I understand what that means but I don’t know what I’m doing wrong that the components are not getting loaded into the container. I’m using Castle.Windsor 2.5.2 and .NET 4.0.
Looking forward to the answers,
David
Following Krzysztof’s advice, here is how to get my simple example going:
That will work.
Krzysztof, we also tried this
and adorned all the classes appropriately but I still got the same error as before. Can you shed some light on this please?