Thanks for reading.
I’m using Unity framework to implement dependency injection in my app (ASP.Net MVC).
Sometimes there are some cyclic dependencies among services that I want to avoid.
So I’m looking for solutions : )
My case
well lets imagine 3 services ServiceSally, ServiceJoe, ServiceJudy
ServiceSally depends on ServiceJoe
ServiceJoe depends on ServiceJudy
ServiceJudy depends on ServiceSally (<< That is kind of weird isn’t it?)
So if you instance ServiceSally, she will need ServiceJoe to be injected, and ServiceJoe will need ServiceJudy and…. BANG!… ServiceJudy will need ServiceSally starting an endless cycle -and very sad love triangle-.
How could I solve this cyclic-loveTriangle case? : /
UPDATE:
My first solution: The LazyJoe
What about to use a wrapper around the services references to delay the injection until they are used?
What do you think?
This depends on what (if any) DI framework you’re using. Spring for example will handle this kind of cyclic dependency as long as not every involved bean (object) is initialized by a constructor. Basically it injects an empty object into (at least) one of the other beans and initializes it later. So the sequence is something like:
This is why initialization-on-construction won’t work with this method (because initialization is deferred). It’s really the only way to handle it. Well maybe you could use some kind of proxy (temporary or permanent) too.
Generally speaking, at least in my experience, cyclic dependencies are symptomatic of a design that is either flawed in some way or in need of simplification.