Injecting a service into another service

Newm picture Newm · Dec 5, 2013 · Viewed 9.1k times · Source

I have an MVC project which has two services an OrganisationService and an AgreementService, my problem is that some of the organisations belong to a group/parent structure, when this is the case I need to get all agreements that belong to any of the organisations within the group.

I already have a method in my OrganisationService that can return a list of all the ids for organisations within the structure:

IEnumerable<int> GetRelatedOrganisationIds(int id)

I could create a method in the AgreementService which accepts the result of this but then I would need to inject both services into my controller and call them in turn e.g.

GetAgreementsByOrganisationIdList(IEnumerable<int> organisationIdList)

Is it ok to inject the OrganisationService into the AgreementService so that it can do the work itself? For example the following method would call GetRelatedOrganisationIds internally:

GetAgreementsByOrganisationId(int id)

Another reason I would like to inject it into the AgreementService is that I would not need to remember to check if the organisation was in a group/parent relationship and look up the ids each time I wanted to get a list of agreements.

I also thought of creating an OrganisationGroupParentInformationProvider and injecting that into the AgreementService instead, I may have spent far too much time thinking about this one.... how would you do it?

Answer

Facio Ratio picture Facio Ratio · Dec 5, 2013

Yes, it would be fine to inject one service into the constructor of another. However, you might want to consider creating an interface for OrganisationService and having your AgreementService depend upon that abstraction, instead.

Another approach would be to create a new service with dependencies on both AgreementService and OrganisationService, and have that new service carry out the responsibility. The new service would of course be injected into your controller.

For guidance, consider whether having it all under AgreementService would violate the Single Responsibility Principle and/or Interface Segregation Principle. If so, make a new service.