开发者

Solve circular references without introducing a new project

开发者 https://www.devze.com 2023-01-16 21:49 出处:网络
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

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 pr开发者_如何学Pythonoject 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.


If you have circular reference then probably you have in solution some one project spitted into two projects, then you can simple merge his code into one project and this second project delete, then you don't introduce new project.

0

精彩评论

暂无评论...
验证码 换一张
取 消