Search code examples
onion-architecture

In Onion Structure, can an infrastructure service call another infrastructure service?


For example, there are two services in the infrastructure layer:

  1. Contact, which is an Elasticesearch service.
  2. PhoneNumber which is a SQL service.

The Contact service needs to get each contact's phone number and return to its caller, so it needs to call the PhoneNumber service.

I am wondering if Contact can call PhoneNumber directly? They are both in the infrastructure layer.

Or, should I let Contact return to the service in the domain layer first, then let the domain layer service call PhoneNumber?

Thanks!


Solution

  • Short answer is that in infrastructure, using a service in another service isn't right pattern, because all services in this layer should be third party services and there should be no relation between them in our infrastructure layer.

    Application layer is responsible for fetching data from infrastructure services. For instance, in this layer, below method could be implemented

    List<string> GetPhoneNumbers(string contactName)
    {
      var phoneNumbers = new List<string>();
    
      var contacts = _contactService.GetContacts(contactName);
      foreach(var contact in contacts)
      {
        var phoneNumber = _phoneService.GetPhoneNumber(contact)
        phoneNumbers.Add(phoneNumber);
      }    
      return phoneNumbers;
    }
    

    _contactService along with _phoneService are the two services in infrastructure layer. The betters name for them would be _contactRepository and _phoneRepository if you use Repository pattern.