Circular Dependency in Two Projects in C#

后端 未结 4 1308
轻奢々
轻奢々 2020-12-20 12:42

I have two projects in a solution named ProjectA (ConsoleApplication) and ProjectB (ClassLibrary). ProjectA has a reference to ProjectB. Generally speaking, ProjectA calls a

4条回答
  •  长情又很酷
    2020-12-20 12:54

    It is actually possible to create projects that have circular dependencies that compile successfully but I strongly recommend against it. Instead, organize your projects so that they have an acyclic dependency graph.

    There are a number of ways to solve this problem, several of which have been mentioned in other answers. One not yet posted is to eliminate the dependency between project A and project B entirely, and create a third project, C, that defines the interfaces that A and B communicate over. That is:

    namespace C
    {
        public interface IFoo { void Frob(); }
        public interface IBar { void Qux(); }
    }
    

    And then make projects A and B reference project C, and make their classes implement IFoo, IBar, and so on. When a method in project A needs to call Frob on an object in project B, it does so by obtaining an IFoo, rather than obtaining some class in B.

    Does that make sense?

提交回复
热议问题