Many IoC containers have a feature of 'auto factories', which generate an implementation of an abstract factory based on its interface. However, it's often a second-class citizen: StructureMap declares only a basic support for the feature, while Simple Injector's author has deliberately omitted auto factories from the library claiming that when applying Dependency Injection correctly, the need for using factories is minimized. This not the only place where I came across a similar view.
However, to me factories seem to be an indispensable element of design when using IoC and writing domain models. Say, a simple made-up example could be:
class Order
{
private ITaxProvider _taxProvider;
public decimal Quantity { get; set; }
public decimal PricePerUnit { get; set; }
public decimal Cost { get; set; }
public Order(ITaxProvider taxProvider)
{
_taxProvider = taxProvider;
}
public decimal GetProfit()
{
// Don't nitpick on this example, please, it's just to show some
// kind of domain object that depends on some kind of service,
// but also has some logic of its own.
decimal grossProfit = Quantity * PricePerUnit - Cost;
decimal netProfit = grossProfit * (1.0m - _taxProvider.GetTaxRate());
return netProfit;
}
}
In this case, every time I create an Order
, say, inside an MVC controller, I will need to use a factory. Eventually, this will most likely be true about any domain object. Even if they may not have any dependencies right now, it is very likely that somebody at some point will request some functionality to behave differently depending on a configuration value, or that some code will be refactored out to separate classes, which may then be decoupled using DI to be testable in separation.
So I am almost willing to roll out factories to take control over initialization of every single domain object. But more experienced developers than myself are saying that I shouldn't need to use factories very often with IoC containers. What should I change in my code's design to make the factories unnecessary?