Let’s now dig deep into the different ways in which dependencies can be introduced into a service. There are three ways in which this can be done,
- Constructor injection – In this way, we pass the instance of the dependency via the constructor of the dependent class
- Method injection – In this case, the instance of the dependency is passed to a method of the dependent class.
- Property injection – Here the instance of the dependency is assigned to a property of the dependent class.
This is one of the solutions to the problem of tightly coupled dependencies between two service implementations. This is one of the applications of the Dependency inversion principle. This is the implementation in which we make the higher level components depend on the abstraction of lower level components instead of the concrete implementation. The dotnet core framework uses the IOC container or the DI container which is a framework that allows the programmers not to worry about the dependency injection and provides the same automatically. The IOC container has three main responsibility
- Registration – This ensures that somehow, the IOC container gets the information about which services are dependent on which services. It gets the map of dependent vs the dependencies.
- Resolution – This allows the IOC container to automatically create the instances of all the dependencies that a particular service has and inject the same whenever it is required.
- Disposition – The IOC container to manage the lifetime and the scope of the instances of the dependencies it has created.