Dependency injection is a technique of implementing inversion of management (IoC), which is a design precept that states that an abstraction layer needs to be used to deal with utility dependencies. In different phrases, as an alternative of sophistication A referencing class B, class A ought to reference an abstraction (i.e., an interface) that class B implements. So, as an alternative of sophistication A relying on class B, class B will rely upon an interface that class A controls. That is the inversion of management.
The usage of interfaces permits builders to simply swap in several implementations of these interfaces. Thus inversion of management and dependency injection allow you to construct functions which can be loosely coupled, modular, testable, and maintainable. Be aware there are a lot of methods to implement dependency injection in ASP.NET Core. Whereas different IoC containers resembling StructureMap and Ninject present extra superior options, ASP.NET Core’s built-in DI container is quick and straightforward to make use of.
Constructor injection vs. the IServiceProvider interface
Each constructor injection and the IServiceProvider interface are strategies for resolving dependencies. Nevertheless, they differ considerably in implications and use circumstances. With constructor injection, the dependencies of a category are handed by means of the category constructor at compile time. With the IServiceProvider interface, the dependencies are retrieved at run time. Thus, IServiceProvider gives an possibility when the dependencies are unknown throughout compilation or might change after compilation.