Injecting a service into another service

20.7k views Asked by At

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?

2

There are 2 answers

2
Facio Ratio On BEST ANSWER

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.

0
Mike Perrenoud On

Is it ok to inject the OrganisationService into the AgreementService so that it can do the work itself?

That wouldn't be injecting it. That would be making it a dependency to it. Regardless, I would say the way you have it is a better architecture because it's more testable. By having the agreement service call the organizations service on its own it's certainly less testable because somewhere you're going to have to inject an instance of the organization service.