Dependecy Injection: Overcoming Cyclic Dependencies

Thanks for reading.

I am using the Unity framework to implement dependency injection in my application (ASP.Net MVC). Sometimes there are some circular dependencies between services that I want to avoid.

So I'm looking for solutions :)


My case

imagine 3 services ServiceSally, ServiceJoe, ServiceJudy

ServiceSally Depends on ServiceJoe

ServiceJoe depends on ServiceJudy

ServiceJudy depends on ServiceSally (<That's pretty weird, isn't it?)

So, if you are a ServiceSally instance, she will need ServiceJoe for injection, and ServiceJoe will need ServiceJudy and ... BANG! ... ServiceJudy will need ServiceSally, starting an endless loop - and a very sad love triangle -.


How can I solve this case with cyclic love?: /

UPDATE:

: LazyJoe

, ?

?

+5
3

, ( ) DI, . Spring, , , bean () . ( ) beans . , :

  • ServiceSally
  • ServiceJoe
  • ServiceJudy
  • ServiceJudy
  • Inject ServiceJudy ServiceJoe
  • ServiceJoe
  • Inject ServiceJoe ServiceSally
  • ServiceSally
  • Inject ServiceSally ServiceJudy
  • ServiceJoe, ServiceJudy ServiceSally, .

-on-construction ( ). . , - ( ).

, , , , - , .

+7

* *. . * * .

+2

I agree with Cletus to some extent, whenever you provide services that depend on each other, it's time to sit down and rethink your design.

If you are doing lazy DI, why are you doing DI at all? One of the benefits of using DI is that you don’t have to worry when your dependencies are initialized, you are just there when you need them.

-2
source

All Articles