Created
October 5, 2012 21:00
-
-
Save jonnii/3842375 to your computer and use it in GitHub Desktop.
castle windsor factory example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Castle.Facilities.TypedFactory; | |
using Castle.MicroKernel.Registration; | |
using Castle.Windsor; | |
namespace castlething | |
{ | |
public class Program | |
{ | |
public interface IMathService | |
{ | |
int Add(int x, int y); | |
} | |
public class MathService : IMathService | |
{ | |
public int Add(int x, int y) | |
{ | |
return x + y; | |
} | |
} | |
public interface ICalculator | |
{ | |
int Run(int x); | |
} | |
public class Calculator : ICalculator | |
{ | |
private readonly IMathService service; | |
private readonly int left; | |
public Calculator(IMathService service, int left) | |
{ | |
this.service = service; | |
this.left = left; | |
} | |
public int Run(int x) | |
{ | |
return service.Add(left, x); | |
} | |
} | |
public interface ICalculatorFactory | |
{ | |
ICalculator Build(int left); | |
} | |
public static void Main(string[] args) | |
{ | |
var container = new WindsorContainer(); | |
container.AddFacility<TypedFactoryFacility>(); | |
container.Register( | |
Component.For<IMathService>().ImplementedBy<MathService>(), | |
Component.For<ICalculator>().ImplementedBy<Calculator>(), | |
Component.For<ICalculatorFactory>().AsFactory()); | |
// resolve it directly | |
var direct = container.Resolve<ICalculator>(new { left = 5 }); | |
Console.WriteLine(direct.Run(5)); | |
// resolve it via factory | |
var factory = container.Resolve<ICalculatorFactory>().Build(5); | |
Console.WriteLine(factory.Run(5)); | |
Console.WriteLine("Done"); | |
Console.Read(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment