2

I have two services and a mediator. If I want the mediator to call AND be called by both services, I think that I need to make them dependencies of each other. This causes a circular dependency error.

Person Depends on Mediator to call Mediator methods

Mediator Depends on Person to call Person methods

Is the only solution to use events or promises? Am I implementing this pattern correctly?

Chris Bier
  • 14,183
  • 17
  • 67
  • 103
  • could you showcase some of your code – Ajay Beniwal Dec 18 '13 at 18:46
  • 1
    Why do you need the mediator to depend on the other services? Cant you just have your services depend on the mediator and once initialized register callbacks inside the mediator or something similar? Difficult to tell without knowing exactly what you want to do. – Beyers Dec 18 '13 at 21:24

2 Answers2

3

this is a bit of a problem that extends beyond angular and into javascript imho.

the standard way to structure mediators to avoid circular dependencies is to use interfaces, but javascript doesn't have interfaces.

in your situation, if you have the mediator injected into the service and vice versa, yes there will be an error.

assuming your mediator is also a service, a work around is not to have dependencies injected into the mediator, but rather have the mediator initialized before it is ever used with the 2 services that you need it to mediate for.

the alternative is not to use a mediator object, but use the publisher/subscriber pattern which is built into angular with $broadcast and $on. imho, this gives even looser coupling than the mediator pattern, so it has my thumbs up

Anton
  • 7,709
  • 5
  • 31
  • 33
  • What does "have the mediator initialized before it is ever used with the 2 services that you need it to mediate for" mean? Any chance of some code to demonstrate? – poshest Oct 05 '14 at 11:50
  • 1
    @poshest the OP tried injecting the 2 Person objects into the mediator, which didnt work because of the circular dependency. the work around is to have something like function initMediator(person1, person2) which initializes the mediator with the 2 objects being mediated between. – Anton Oct 06 '14 at 00:01
  • @Anton, please edit your answer to accommodate an implementation of "*but rather have the mediator initialized before it is ever used*". Please see my question: http://stackoverflow.com/questions/37889533/javascript-angular-mediator-pattern-tactics-for-obviating-circular-dependen – Cody Jun 17 '16 at 20:10
1

Only your services which utilize Mediator should depend on Mediator. A service which publishes events injects Mediator. A service which subscribes to events injects Mediator and registers callbacks contained within the service. The Mediator should not depend on either service, it should only contain map a publishing events to a list of callback references.

See the Mediator in Angular example I wrote here

SirTophamHatt
  • 1,581
  • 17
  • 23