TomCaps
TomCaps

Reputation: 2527

Service Class should reference other Service Class or just reference other Repository Class?

I have a WCF Service class PersonService which can save Person and his/her Address information into Person and Address tables in the database.
Here are two versions of the implementation:

version 1 (Repository Version)

    [ServiceContract]
    class PersonService
    {
        private IPersonRepository _personRepository;

        //by referencing other **repository**
        private IAddressRepository _addressRepository;

        private PersonService(IPersonRepository personRepository, IAddressRepository addressRepository)
        {
            _personRepository = personRepository;
            _addressRepository = addressRepository;
        }

        public void Add(Person person){
            _personRepository.Add(person);

            //by calling method from the **repository** layer
            if(!_addressRepository.Contains(person.Address))
            {
                _addressRepository.Add(person.Address);
            }
        }
    }

version 2 (Service version)

[ServiceContract]
    class PersonService
    {
        private IPersonRepository _personRepository;

        //by referencing other **service**;
        private IAddressService _addressService;

        private PersonService(IPersonRepository personRepository, IAddressService addressService)
        {
            _personRepository = personRepository;
            _addressService = addressService;
        }
        public void Add(Person person)
        {
            _personRepository.Add(person);

            //by calling method from the **service** layer
            if (!_addressService.Contains(person.Address))
            {
                _addressService.Add(person.Address);
            }
        }
    }

Which of them is a better practice? Should a Service class like PersonService be coupled more with interfaces in its same layer,or a lower layer such as the Repository layer? and why?

Upvotes: 2

Views: 322

Answers (1)

Claudiu Mihaila
Claudiu Mihaila

Reputation: 1332

Both versions are the same. The interface name should not suggest implementation details.

The PersonService class doesn't care who is implementing the interface (repository or service) as long as it gets an object that implements the interface.

In the end this is the reason why you use an interface and not directly the class that implements it.

If you are refereeing how to do the dependency injection I would pass the service in case you have some caching or other processing in the AddressService.

Upvotes: 1

Related Questions