Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection and Circular reference

Tags:

oop

tdd

I am just starting out with DI & unit testing and have hit a snag which I am sure is a no brainer for those more experienced devs :

I have a class called MessageManager which receives data and saves it to a db. Within the same assembly (project in Visual Studio) I have created a repository interface with all the methods needed to access the db. The concrete implementation of this interface is in a separate assembly called DataAccess.

So DataAccess needs a project reference to MessageManager to know about the repository interface. And MessageManager needs a project reference to DataAccess so that the client of MessageManager can inject a concrete implementation of the repository interface. This is of courser not allowed

I could move the interface into the data access assembly but I believe the repository interface is meant to reside in the same assembly as the client that uses it

So what have I done wrong?

like image 273
ChrisCa Avatar asked Sep 21 '26 00:09

ChrisCa


1 Answers

You should separate your interface out of either assembly. Putting the interface along with the consumer or the implementor defeats the purpose of having the interface.

The purpose of the interface is to allow you to inject any object that implements that interface, whether or not it's the same assembly that your DataAccess object belongs to. On the other hand you need to allow MessageManager to consume that interface without the need to consume any concrete implementation.

Put your interface in another project, and problem is solved.

like image 94
Jon Limjap Avatar answered Sep 24 '26 15:09

Jon Limjap



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!