I've been studying onion architecture for a couple of days. I understand that dependencies should always go toward the center and how to use dependency injection to accomplish this. But I have a couple of questions I still couldn't figure out.
Can a model (or entity) reference a repository interface or a service interface?
Eg: an Order
entity has a DeliveryCity
relationship established through Oder.DeliveryZip
property, which is not a foreign key, but is unique. To get the City for a zip, I must call ICityRepository.FindByZip(zip)
I have the following code in my model
class Order
{
. . .
[Inject]
public ICityRepository CityRepository { get; set; }
private City _dCity;
public City DeliveryCity {
get {
if (_dCity == null)
_dCity = this.CityRepository.FindByZip(this.DeliveryZip);
return _dCity;
}
}
. . .
}
What would be the problems of the above code? Should it use a domain service instead?
Should the domain services implementations be defined inside the core or at the infrastructure layer?
This is where Factories fit into the domain. An OrderFactory can take dependencies, such as a dependency on the IOrderRepository as well as a dependency on ICityRepository. When the factory is used to create (or reconstitute) an Order entity, the factory can lookup the City and set the Order property accordingly. Or, as herzmeister suggests, set it using Lazy so the lookup is only performed if/when needed.