Dependency Injection(DI) in .NET

Dilan Perera
2 min readSep 5, 2021

What is DI?

DI is a popular design pattern which is a great way to reduce tightly coupling between software components.

What is tightly coupled?

Direct Dependency

Above is a three tier architecture where all layers are tightly coupled. Which is Client uses Business Layer and Business Layer uses Data Access Layer so on. Hence, if the Business Layer is broken then the whole system collapse. Or if a modification has been done for the Business Layer, then that will affect on both Client and the Data Access Layer.

It will be very problematic to change the development of this kind of scenario in compile time and run time, when a team is working on a solution like above.

We use Dependency Injection to overcome this issue.

How DI solves the tightly coupled issue?

Inverted Dependency

Now the Class has the reference to an Interface and depends on it. If the Class B and Class C are not there in the compile time, it doesn’t affect on Class A since it depends on the Interface B.

We can inject the implementation of Class B to Interface B at the runtime and then Class A can use the functionality. This is called as Inverse of Control (IOC).

We use a IOC container (DI container)to arrange our interfaces and classes.

Ex: Unity, Autofac, Ninject etc..

DI pattern

Here the Client will be using the Service. The Injector will create an instance of the Service and inject to the Client. So that the direct dependency between Client and Service is gone, since the Client references an interface of a Service.

And the implementation of the Service doesn’t matter if we ask to inject and the current implementation of it, the Injector will Inject it to the Client.

So the Injector takes the responsibility of Client uses the Service here.

This is the working pattern of Dependency Injection.

DI Types

Constructor Injection - Inject the instance of the dependency class in the constructor of the dependent class.

Property Injection - Inject the instance of the dependency class in a property of the dependent class.

Method Injection - Inject the instance of the dependency class in a method/action of the dependent class.

So it covers about the Dependency Injection.

Thank you!

--

--