For simplicity I create the following scenario to show you how to use dependency injection in a simple console application.
I am using Castle Project
- Install the NuGet: Install-Package Castle.Core -Version 4.4.0
I have the following interfaces:
public interface ITranslate
{
string GetMenu();
}
public interface IFood
{
string GetFood();
}
Than the classes the implement the interfaces:
public class FrenchCuisine : IFood
{
public string GetFood()
{
return "Soupe à l'oignon";
}
}
public class ComidaBrasileira : IFood
{
public string GetFood()
{
return "Feijoada";
}
}
public class FrenchTranslator : ITranslate
{
private readonly IFood food;
public FrenchTranslator(IFood food)
{
this.food = food;
}
public string GetMenu()
{
return this.food.GetFood();
}
}
public class PortugueseTranslator : ITranslate
{
private readonly IFood food;
public PortugueseTranslator(IFood food)
{
this.food = food;
}
public string GetMenu()
{
return this.food.GetFood();
}
}
If I put everything together in my Console Application
:
using Castle.Windsor;
using System;
using Component = Castle.MicroKernel.Registration.Component;
namespace StackoverflowSample
{
internal class Program
{
//A global variable to define my container.
protected static WindsorContainer _container;
//Resolver to map my interfaces with my implementations
//that should be called in the main method of the application.
private static void Resolver()
{
_container = new WindsorContainer();
_container.Register(Component.For<IFood>().ImplementedBy<FrenchCuisine>());
_container.Register(Component.For<IFood>().ImplementedBy<ComidaBrasileira>());
_container.Register(
Component.For<ITranslate>().ImplementedBy<FrenchTranslator>().DependsOn(new FrenchCuisine()));
}
private static void Main(string[] args)
{
Resolver();
var menu = _container.Resolve<ITranslate>();
Console.WriteLine(menu.GetMenu());
Console.ReadKey();
}
}
}
Expected result
Soupe à l'oignon