Interfaces between multiple projects

interfacesopen-closeproject-structure

I'm slightly confused over the following:

ProjectA 
-------- GetUsers (Implements IDBConnector)
-------- IGetUsers
-------- UserModel

ProjectB 
-------- Main 

I have two projects one main project (project B) and another which gets data from a database (project A). Project A has an interface which the main class makes use of. The GetUsers class is then injected within the main class of type IGetUsers.

This means there is a dependency of Project A for Project B as Project B needs to know how the interface is defined and the class definition itself. I am fine with this from a code standpoint but I can't help thinking that the interface should be kept somewhere else as it is essentially a contract and I am trying to follow the open/closed principle i.e. I shouldn't have to touch the main class to change how the database interaction is dealt with. In my example however if I remove Project A I lose the interface definition and I would have to modify the Main class.

I would have thought that Project B would be a good place to keep the interface but this would result in a circular reference as Project A would need to reference Project A for the interface declaration and vice versa for the class implementation.

The other option is to have a separate project for interfaces which I have seen mentioned in this question:

Sharing classes or interfaces between different projects

But to me this seems a little silly to have this example interface in a whole separate project while there is only one interface at current.

Best Answer

You almost have you answer here:

I would have thought that Project B would be a good place to keep the interface but this would result in a circular reference ...

Following the Dependency Inversion Principle, interfaces should be defined by user, not the implementer. As you said in your question, the interface is essentially a contract; in order to invert the dependency, the user has to define the contract, so that the implementer depends on it. This contrasts with the normal flow of dependency, where the user depends on the contract that is forced on it by the implementation.

So, back to organizing the separate projects: If B is the user of the IGetUsers interface, then it must be the one to define it. If A provides an implementation of that interface, then it must depend on B. And now, not only to avoid circular references, but also to free B from any future dependencies that the may come, you can define a third project, C, which has the sole responsibility of composing the system out of the small modular pieces.

This concept is known as composition root, and is ideally the place where all dependency injection should live, leaving A and B outside the bounds of a dependency injection framework, if one were to use it.