Reputation: 567
I am trying to wrap my head around the concept of Dependency Injection. I have a visual studio solution. I have split it into 3 projects: DataAccessLayer, ServiceLayer, BusinessLogicLayer.
The ServiceLayer acts as a link between BusinessLogic and DataAccess hiding things like SQL and LINQ statements from the BusinessLogic.
Now, many tutorials online recommends using DependencyInjection to use the classes in the ServiceLayer in my BusinessLayer. I believe, the reason is so that the BusinessLayer is loosely coupled with the ServiceLayer. I, however, do not fully understand how to implement this when these two layers (and their corresponding classes) are in different projects.
According to online tutorials, I will have my classes in ServiceLayer implement an Interface which is what will be referred to in my BusinessLayer. But which project should this interface be defined? It makes sense that this interface is defined in the ServiceLayer. But wouldn't having a reference to this interface from the BusinessLayer cause a tightly coupled logic between these projects? Would that take away the benefit of Dependency Injection?
I hope someone can give me a "Dependency Injection for Dummies" kind of answer for me explaining where my understanding is wrong. Thank you in advance :)
Upvotes: 12
Views: 8723
Reputation: 8450
Dependency Injection is a great thing, because it makes your code independent from implementations of other pieces of code. All dependencies should be injected via constructor(sometimes property) in which you only declare interfaces, not implementations.
In this case you are able for example to inject fake implementation to run unit tests. Also you are able to write multiple versions, for example you can support multiple databases with a common interface and according to user's choice you inject a proper implementation.
Now how to achieve it. You could extract interfaces to another project for example "Common". This would prevent you from adding references to implementations, where you don't need them. Then your BusinessLayer and ServiceLayer would reference to Common.
You'd have the following projects:
You don't have to implement your own IoC and DependencyInjection. You could check out for example: Caliburn.Micro - I really like this framework.
Upvotes: 8