Search code examples
c#.netcircular-dependencycircular-referencedesign-principles

Circular Dependency among two Projects of Different Solution


Suppose there are two .net projects not under same solution. ProjectA is under solution1 and ProjectB is under solution2. ProjectA has a reference of ProjectB and ProjectB has reference of ProjectA. There are two classes ProjectA_Class and ProjectB_Class. ProjectA_Class creates the object of ProjectB_Class and ProjectB_Class creates the object of ProjectA_Class.

namespace ProjectB
{
    public class ProjectB_Class
    {
        public ProjectB_Class()
        {
            ProjectA_Class projA = new ProjectA_Class();
        }
    }
}

namespace ProjectA
{
    public class ProjectA_Class
    {
        public ProjectA_Class()
        {
            ProjectB_Class projB = new ProjectB_Class();
        }
    }
}

I am confused about circular dependency. Isn't it creates a circular dependency between two classes though they are not in the same solution? We know if this two projects reside in the same solution Visual studio won't allow us to reference ProjectA in ProjectB and ProjectB in ProjectA as it creates circular dependency. Isn't it create circular dependency among two projects still though they are not in the same solution? Suppose, there is a class C in ProjectA who creates an object of ProjectB_Class and ProjectB_Class does not use any instance of Class C. Isn't it a circular dependency as ProjectA and ProjectB both has reference of each other?

Update 1 Can you please explain the condition of circular dependencies?


Solution

  • If we're talking about circular build dependency, then that is the problem when project A depends on something in project B, for example by referencing a class in project B. And at the same time Project B is dependent on project A, because it references a class or something in project A. The problem with this is that the build system can't figure out which project to build first, and which to build second.

    But you have a more weird kind of circular dependency in your posted code. The constructors of your two classes try to instantiate the other class, so A instantiates B which instantiates A which instantiates B which ... You get the idea.

    EDIT:

    Circular build dependency is, at least for all build systems I'm aware of, 100% dependent on how the projects reference each other. Visual Studio solutions are not involved at all, so it doesn't matter if the two projects are in the same solution or different solutions or are maybe even projects that are not part of a Visual Studio solution, for example machine-generated projects.

    If you're not using an automated build system, but instead building the projects manually, then you are the build system. And how will you decide which project to build first and which to build second?