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?
You need to define a third assembly that will contain the interfaces. IMHO, there's no other way.
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:
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With