我建议您在设计中引入另一层--应用程序层。该层的职责是转换命令(或者显式封装在命令对象中,或者隐式传递为
int ingId, double quantity
)进入域模型调用(
Recipe.AddIngredient
通过这样做,您将把通过id查找成分的责任转移到域之上的一层,在那里您可以直接安全地使用存储库,而不会引入不必要的耦合。转化后的解决方案如下所示:
public class ApplicationLayer
{
private readonly IRecipeRepository _recipeRepository;
private readonly IIngredientRepository _ingredientRepository;
/*
* This would be called by IoC container when resolving Application layer class.
* Repositories would be injected by interfacy so there would be no coupling to
* concrete classes.
*/
public ApplicationLayer(IRecipeRepository recipeRepository, IIngredientRepository ingredientRepository)
{
_recipeRepository = recipeRepository;
_ingredientRepository = ingredientRepository;
}
public void AddIngredient(int recipeId, int ingId, double quantity)
{
var recipe = _recipeRepository.FindById(recipeId);
var ingredient = _ingredientRepository.FindById(ingId);
recipe.AddIngredient(ingredient, quantity);
}
}
现在简化的Recipe类如下所示:
public class Recipe : AggregateObject
{
public void AddIngredient(Ingredient ingredient, double quantity)
{
Ingredients.Add(new OriginalIngredient()
{
Ingredient = ingredient,
Quantity = quantity
});
}
}
希望有帮助。