Patterns Simpl: Dependency Injection

"In software engineering, dependency injection is a technique whereby one object supplies the dependencies of another object. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it."

A better quote for the initiated to DI/IoC would be:

"Dependency Injection was originally called Inversion of Control (IoC) because the normal control sequence would be the object finds the objects it depends on by itself and then calls them. Here, this is reversed: The dependencies are handed to the object when it's created. This also illustrates the Hollywood Principle at work: Don't call around for your dependencies, we'll give them to you when we need you." -javaworld.com

In .NET, .resx resource files that contain different inputs based on the culture settings of the client is an example of DI.

Another simple and clear example of Dependency Injection in action is in ASP.NET Core Authentication.

The built-in Authentication Controller and the Startup.cs Configure() method are designed to work with an interface and not one specific/concrete class of authentication provider. It uses IAuthenticationSchemeProvider which provides a generic and flexible structure that leaves the specific type of authentication up to the developer(s) (Google, Microsoft, Twitter, GitHub, Instagram, Facebook, etc.).

These different authentication types/providers are what the IAuthenticationSchemeProvider depends on to handle the authentication process for ASP.NET Core applications.

The developer injects the dependency(s) of his or her choice.

A common form of Dependency Injection is Localization of display text in applications

Loose coupling is key for interoperability with other apps and services, if your dependencies are more generic, your system is more extensible

No comments: