简体   繁体   中英

Place for declaring interface

Assume a program on C# (or any other language that has an abstraction of interface ) where first part (A) and second part (B) depend on the third part (C). For example assume Visual Studio solution with three projects where class ClassA in project A and ClassB in project B depends on instance of ClassC in project C. I want to separate interface from implementation, so that I create interface IClassC and use it in ClassA and ClassB . In which project I should declare the interface IClassC ?

It sounds like ProjectC doesn't depend on ProjectA or ProjectB, but clearly needs to know about the interface (so that the class can implement it). Therefore it has to be in ProjectC or some other project that every project depends on. (You could have a separate project just for the interfaces, but I've rarely found that to be useful.)

在Project C或单独的接口项目Project I中

Most of cases it would be in project C, but what if you want assembly is plugin-able, it means you can change the implementation of interface C. And you don't want to re-build project A and B each time when you change code in project C.

With this case you need to apply DIP principle to inverse dependency, so interface C should be in new project call IC. The dependency will change from:

A -> C
B -> C

To:

C -> IC
A -> IC
B -> IC

So with this way when you change code in C or replace C with C', it also does not affect to A and B.

You can declare it in the ClassC project, this would be fine from a referencing point of view.

You could also place it in its own interfaces project, which would enable you to reference the interface separately in, for example, test projects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM