I have big, fat and ugly legacy program. One task I had to accomplish was adding a new class to project A. Project B references project A, but the functionality I need to add depends on a method of a class in project B. Of course, I can’t reference project B from A, because that would create a circular reference. In a similar situation, my approach was to create project C and move the dependencies from A and B into it, and have both A and B reference it.
But, for this particular task it would require moving so much code that it would create a huge mess in the solution.
For now, I’m passing the instance of that needed class boxed in an object and using reflection to access the method I need at runtime.
Is there any other (better) way to solve this without moving code to a project C?
Create an interface defined in project A which contains the method signature of the method in project B that you want A to be able to call. Implement that interface on your class in project B.
All that remains then is to provide a way for B to tell A “I’m here! Call me!”. You could do that by defining a static method in A that takes the interface as a parameter and holds onto it in a variable in project A. B can call that method, passing an instance of the class that implements the interface. When A needs to call B, it calls the interface reference stored by that registration function.