Class C from assembly A1 implements interface from assembly A2. When using C, need to reference both A1 and A2

懵懂的女人 提交于 2019-12-13 06:07:08

问题


This is by design, according to the answers in this SO question

But I really don't want to reference both assemblies, it feels like I'm breaking encapsulation (the users of A1 shouldn't know that A1 uses A2 for its implementation...)

I thought of moving the interface definition to another assembly, let's call it "Core", and have both A2 and A1's client reference it. This feels cleaner to me.

My question is: Is this good design? Or is there a standard .NET solution to this that I'm not aware of? On the other hand, I worry that "Core" will end up being a nasty mix of totally unrelated interfaces... What do you think?


回答1:


First of all, this doesn't break encapsulation.

Encapsulation means that the implementation details are not relevant - so long as you program to the interface, encapsulation is intact.

Secondly - if you want to use both the interface and implementation, you need to reference the assemblies both are in (disregarding plug-in architectures). How else would your code work? If there is no reference to the implementation, you can't instantiate a concrete type. If there is no reference to the interface, you can't use it in your code.




回答2:


C# does not have private inheritance. If class A1 implements interface A2, then that is public information, which is exposed to users of class A1, exactly as though A2 were a base class and not an interface.

Yes, you must reference both assemblies.




回答3:


I solved it to my satisfaction, please tell me what you think:

(Warning: this is IDE-specific, don't know if I could pull it off in, say, SharpDevelop)

  1. In A1, instead of referencing the A2 assembly, in Visual Studio, right-click the A1 project and select "Add Existing Item". Select the interface file. Before pressing the Add Button, notice it's a dropdown button: drop it and select "Add as Link". If you don't do it this way, you'll have to mantain multiple copies of the interface, which is a hassle

  2. Remove the reference from A1 to A2 (if all you used from it was the interface)

  3. Voila! A1's clients only need a reference to A1. I think this is because now the interface is a type which is defined in both the A1 and A2 assemblies. I don't think that endangers manteinance, because the interface is still defined in only one source code file. Ok, its's compiled into two assemblies, so it's a sort of "binary duplication", but I don't think that's bad... Do you?



来源:https://stackoverflow.com/questions/7745249/class-c-from-assembly-a1-implements-interface-from-assembly-a2-when-using-c-ne

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!