Circular dependency in a pick pattern using C #

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

Mediator and Colleague components / classes are in different assemblies, and as a mediator template, it is required that both components (classes) use each other. The problem occurs when referring to 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} } } 

how Mediater and colleague are in different namespaces and nodes, how to resolve circular dependency?

+6
source share
3 answers

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

+4
source

If two classes are closely related to each other to implement the template, why are they in separate assemblies? Please note that it is possible to implement a mediation template without such a circular dependency. Usually you do this in one of two ways:

  • Registration of delegate callbacks with the help of an intermediary, so that you can implement your โ€œColleagueโ€ in various ways, not knowing what the Mediator should know about them. It is much simpler than before, with anonymous methods and lambda expressions to clearly express the callback logic.

  • Provide some standard IColleague interface in the same assembly as the Mediator, with the necessary callbacks, and determine which specific implementation you will need in the consuming assemblies.

+2
source

I would move IColleague to a namespace / assembly containing reseller code. Assuming there is no other relationship between them. Otherwise, move both of them depending on which one is currently dependent.

+1
source

Source: https://habr.com/ru/post/896894/


All Articles