Dependency injection on .NET

Wednesday, March 30, 2022


I will try to explain Dependency Injection, from the practical point of view of someone like me who has discovered software engineering concepts. A dependency is an object and its resources such as functions, methods, definitions, etc. that are required in the current code; to give an example, a log system, a connection to a database, the current security context, etc.

Let's take the example of the connection to the database.

Unlike a classical approach where we create this connection in our class when we occupy it, we could "inject" this connection (or dependence) into the previously created class and our class could use this object within its context without worrying about creating it and perhaps destroying it.

We must clarify a detail, for differences the injection of simply passing parameters by reference is that in the injection of dependencies we pass an interface, an abstract definition of the object, in this way we abstract the implementation and creation of the object, we can in the future modify the implementation of that object in a simple way.

Returning to the example of the connection to the database, the consumer class only has one interface for the connection and should not worry for example in the initialization of the connection, it will be indifferent if for example we change from an instance of SQL server to one of Oracle.