Dependency Injection And Inversion Of Control C# - Part One (Concept)

Dependency Injection is one of the "SOLID" principles which helps to decouple the code by making sure that we depend on abstractions, not on the implementation of concrete classes. The concept is the inversion of control.

Inversion Of Control - It was considered as a programming style used to invert the flow of control.

In a procedural language, a code that consumes dependent code is in control of the process, i.e., it knows exactly what method to use and sometimes, what the implementation is.

To achieve a goal, one class needs to consume some other class. Now, the question is, Does the consumer class really need to know about dependency on the dependent class?


It is enough for a consumer class to know the properties, behavior etc. of the dependent class rather than knowing which is the dependent class having those properties, behavior etc.

I mean, we can abstract the behavior which is required by a consumer in the dependent class and allow a consumer class to use that instance instead of a dependent class directly. In this way, consumer class doesn't need to know any specifics about dependent class.

Here, B (dependent class) is implementing an interface IY and A (consumer class) uses an instance of IY. So, A is using B but it does not know that. Only A knows that it uses some class that implements IY, can be A, AB, or ABC which implements IY.

Advantage Of IOC

It provides decoupling, A is not dependent on B. We won't write any code in A which relies on the implementation of B; hence on any changes in B, we won't make any changes in A.

We can change in "A" which is the implementation of IY. It uses without changing anything in A.

Suppose B implements the IY interface and uses it to send email in some format. F1 and C are other classes that implement IY interface and sends email in another format F2. Suppose, A now wants to send email in format F2 rather than format F1. We don't need to modify anything in A.

Another benefit is the code isolation in unit testing.

Now, A relies on C rather than B because it wants to use format F2 instead of format F1 and we don't want our test case to fail. With IoC, A doesn’t rely on B but on an implementation of IY that just happens to be B.

Same way, in unit testing, we can change it so that A uses a different implementation of IY, such as a mock object which sends mail in some mock format, and which also allows us to check that A has used it in a correct way.

Now, you know the concept. In my next post, I will explain this through some exercises.

Link to be updated soon for the second part.

Next Recommended Reading Factory Design Pattern In C#