I'm currently trying to refactor some rather complicated object graph to use dependency injection. I'm using C# and StructureMap, but the problem isn't really technology specific. I understand the basic principle, but drawing blanks on how would I resolve a dependency like this:
public class Food
{
public Food(IIngredient ingredient)
{
this.foodProcessor = new FoodProcessor(this);
}
// ... Lots of things to customize food
public void BuildFood()
{
this.foodProcessor.Process();
}
}
public class FoodProcessor
{
public FoodProcessor(Food f)
{
this.food = f;
}
public void Process(){
// yummy
}
}
In that case, a FoodProcessor
on its own doesn't make sense. I can't process null
or empty food. On the other hand, new
in ctors are not good (right?), and should be injected as a dependency.
Is the new
okay in this case, or is it possible to refactor this without major changes to my application?
FoodProcessorFactory
class with acreate
method which takes aFood
and construct aFoodProcessor
. You could also not construct aFoodProcessor
with aFood
, and instead pass it as an argument to theProcess
function. Or maybeFoodProcessor
is just an implementation detail which is irrelevant for the outside world, then in this case it should just be a private class which would be tested byFood
's public interface. I think there may be missing more information to accurately answer your question. – Vincent Savard Jan 13 '17 at 13:46