Dependency Injection and Inversion of Control on .Net Core
Do you know about the terms Dependency Inject and/or Inversion of Control? No? Let’s go to talk about it! I’ll explain to you how and why do you need to use these patterns. And finally, we’ll develop a .Net Core simple application that uses these concepts.

Firstly, what do you think to learn the theory? Let’s start learning a little bit about Dependency Injection!

Dependency Injection

Dependency Injection, also known as DI, is a Design Pattern used to avoid coupling inside your code. According to the best practices in software development and part of one of S.O.L.I.D. principles, a class should depend on abstractions and not from concrete classes.

A dependency is an object that your class needs to do the work, in other words, this object isn’t created inside your class. The dependency is injected into a class that uses it, so the dependency is required to be external. The object instantiation (that is the dependency) must not be inside the class, but outside it. Look below a simple example:

In this case, when I instantiate the LeaderboardServiceManager class, I need to pass an IMapper type instantiate. Look, the constructor receives a parameter (mapper) and its value is set to a variable (_mapper) which will be used in the other functions of this class.

Benefits of using it:

Low coupling

Simplicity

Ease of maintenance

Ease to learn about the code/project

Ease to test your code

Exists three most common types of Dependency Injection:

1) Constructor

It is the most common type of DI. When the class’ constructor receives a class or an abstraction of another class as a parameter it is a DI. Look at another example below:

In this case, I receive an ISmtpClient type instantiate by the constructor to use it in some function of my class.

2) Getter and Setter

Injection by properties (get and set). It occurs when exists a class or an abstraction exposed as property. Look the example below:

We have a property SmtpClient of ISmtpClient type, so to this property must be attributed a valid value.

3) Interface Implementation

When the class has a method who receives an abstraction by parameter. In the following example, the method setSmtpClient receives the smtpClient variable of the ISmtpClient interface type (an abstract type).

4) Service locator

It is often called a container. It happens when you have a container that provides many instances and you can just request a specific instance to it. Like this:

First, we should have a class to register and provides the instances

Second, in another part of your code, we can register all the instances

And finally, we can use it like this

And next, let’s go to talk about the Inversion of Control!
['Alex Alves']
['C Sharp Programming', 'Best Practices', 'Net Core', 'Inversion Of Control', 'Dependency Injection']