Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular Dependency in mediator pattern using c#

I have a question regarding mediator pattern that I want to implement in my application(using C#). While implementing the pattern in my code I came across a circular dependency. The structure of the classes as follows:

Mediator and Colleague components / classes are in different assemblies and as mediator pattern requires both components (classes) to use each other. The problem arises when referencing each other.

Consider the code below:

namespace Mediator
{
   public abstract class IMediator
   {
      public IColleague colleague{get;set;}
      void Register();
      void Send();           
   }
   public class MediatorA:IMediator
   {        
     void Register(){//code here}
     void Send(){//code here}       
   }
 }

namespace Colleague
{

    public abstract class IColleague
    {
        IMediator mediator;
        void Send();
        void Recieve();       

    }
    public class ColleagueA:IColleague
    {

        void Send(){//code here}
        void Recieve(){//code here}       

    }
}

as Mediater and colleague are in different namespaces and assemblies, how to resolve the circular dependency?

like image 687
GeekM Avatar asked Sep 08 '11 15:09

GeekM


3 Answers

You need to define a third assembly that will contain the interfaces. IMHO, there's no other way.

like image 186
Seb Avatar answered Nov 11 '22 14:11

Seb


If two classes are fairly tightly coupled to each-other in order to implement a pattern, why are they in separate assemblies? Note that it's possible to implement the Mediator pattern without having this sort of circular dependency. You typically do this by one of two ways:

  1. Registering delegate callbacks with the Mediator so that you can implement your 'Colleague' in various ways without having the Mediator need to know about them. This is much simpler than it used to be, with anonymous methods and lambda expressions to cleanly express callback logic.

  2. Provide some standard 'IColleague' interface in the same assembly as the Mediator with the necessary callbacks and define whatever concrete implementation you need in the consuming assemblies.

like image 4
Dan Bryant Avatar answered Nov 11 '22 14:11

Dan Bryant


I would move the IColleague into the namespace/assembly containing the mediator code. Assuming there was no other dependency between the two. Otherwise move both of them to whichever assembly is currently being depended on.

like image 2
Sign Avatar answered Nov 11 '22 13:11

Sign