Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvc - reusing service behavior

I have been working on a MVC-EF application. We use DI container to inject dependencies into controllers, services, and repositories i.e across the UI-Services-DataAccess layers.

My question is regarding DI in services. One thing I have been confused about recently has been arisen from the need to use the behaviour (aka methods) that was implemented in one service in another service.

As far as I know, one service should not take dependency upon another because that would finally be leading closer to circular dependency and hence causing issues for DI container down the line.

So my question is, how should I work this out?

Should I be implementing the needed behaviour in second service (as part of its own methods) or I can somehow reuse it from the already implemented first service?

Can DI container help me in this regard?

Or is it that the way out is to outsource behaviour implemented in services into a separate Business Logic Layer, so it is available to each of the services? BTW, we currently do not have a separate BLL.

like image 890
user3536100 Avatar asked Dec 18 '25 22:12

user3536100


1 Answers

As far as I know, one service should not take dependency upon another because that would finally be leading closer to circular dependency and hence causing issues for DI container down the line.

This isn't quite true. In general, your objects refer to each other, forming a graph. When we discuss Dependency Injection, we normally call it a Dependency Graph.

As long as this graph is a Directed Acyclic Graph, all is good. The keyword here is acyclic, but it doesn't preclude reuse. You can have several services that use a single instance of another service; that just means that the service is shared.

Dependency Graphs can be as shallow or as deep as required, as long as they are acyclic, you can compose dependency graphs with confidence.

like image 108
Mark Seemann Avatar answered Dec 21 '25 12:12

Mark Seemann