Just another library to implement the factory method pattern
Create your classes
public class Customer
{
public string Name { get; set; }
public int Age { get; set; }
}
public interface IDoSomething
{
bool Apply();
}
public class DoSomething : IDoSomething
{
public bool Apply()
{
return true;
}
}
public class DoSomethingLessThan18 : IDoSomething
{
public bool Apply()
{
return true;
}
}
Create a class to setup the factory
public class ObjectFactoryConfigurationSource : AbstractObjectFactoryConfigurationSource
{
public ObjectFactoryConfigurationSource()
{
For<Customer, IDoSomething>().Create<DoSomething>().When(x => x.Age >= 18);
For<Customer, IDoSomething>().Create<DoSomethingLessThan18>().When(x => x.Age < 18);
}
}
Use the factory
var customer = new Customer(){Age = 25};
var services = factory.Create<Customer, IDoSomething>(customer);
var container = new WindsorContainer();
container.AddFactory(c=>
{
c.AddSource<ObjectFactoryConfigurationSource>();
c.AddSingleton<IDoSomething, DoSomething>();
c.AddSingleton<IDoSomething, DoSomethingLessThan18>();
});
var factory = container.GetFactory();
var container = new ServiceContainer();
container.AddFactory(c=>
{
c.AddSource<ObjectFactoryConfigurationSource>();
c.AddSingleton<IDoSomething, DoSomething>();
c.AddSingleton<IDoSomething, DoSomethingLessThan18>();
});
var factory = container.GetFactory();
var container = new ServiceCollection();
container.AddFactory(c=>
{
c.AddSource<ObjectFactoryConfigurationSource>();
c.AddSingleton<IDoSomething, DoSomething>();
c.AddSingleton<IDoSomething, DoSomethingLessThan18>();
});
var provider = container.BuildServiceProvider();
var factory = provider.GetFactory();