问题
I've a Customer entity that has an referente to City:
public class Customer
{
public int CustomerId { get; set; }
public int CityId { get; set;}
}
Then, the following application service:
public class CustomerService
{
private readonly ICustomerRepository customerRepository;
public CustomerService(ICustomerRepository customerRepository)
{
this.customerRepository = customerRepository;
}
public void RegisterCustomer(Customer customer)
{
//Do another things...
customerRepository.Save(customer);
}
}
To register a new customer the service consumer would have to have access to a listing of cities to put in CityId, such as get the list of cities to fill a combobox.
Thus it would be necessary provide a list city operation.
Should i add this operation to CustomerService?
Like:
public class CustomerService
{
private readonly ICustomerRepository customerRepository;
private readonly ICityRepository cityRepository;
public ServicoCliente(
ICustomerRepository customerRepository,
ICityRepository cityRepository)
{
this.customerRepository= customerRepository;
this.cityRepository= cityRepository;
}
public void RegisterCustomer(Customer customer)
{
customerRepository.Save(customer);
}
public List<City> ListCities()
{
return cityRepository.GetAll();
}
}
Or create a new Service:
public class CityService
{
private readonly ICityRepository cityRepository;
public CityService(ICityRepository cityRepository)
{
this.cityRepository= cityRepository;
}
public List<City> ListCities()
{
return cityRepository.GetAll();
}
}
In the latter case the consumer should have references two services to be able to complete one operation: RegisterCustomer.
Which approach to follow? What are the advantages and disadvantages of this?
回答1:
This is a code organization issue and has little to do with DDD.
public class CustomerService {
public List ListCities() { return cityRepository.GetAll(); }
}
There's an obvious mismatch here -- you don't expect from a Customer service public interface method to return cities. This breaks the principle of least surprise and will cause a lot of searching and head scratching for generations of developers to come.
A dedicated service seems like a better idea to me.
来源:https://stackoverflow.com/questions/29009290/application-services-composition