Dependency Injection in NetCore

jpblancodb

JPBlancoDB

Posted on November 9, 2019

Dependency Injection in NetCore

Dependency Injection in NetCore

Dependency Injection [DI] is a pattern that gives the implementation of a class to an object without needing a Factory or the object knowing how to instantiate it with the intent to decoupling these objects.

We are going to describe the purposes of the three types of patterns available in NetCore: “Singleton”, “Scoped” and “Transient”.

The purpose of Singleton is to instantiate your object only once and then whenever you need that object, you will use the same implementation. This is useful for example for caching.

Then, we have Scoped. When it is applied your object will be instantiated once per request lifecycle. This is useful for example for Repositories or Services.

Lastly, we have Transient. This is the most common of the three because it is going to be instantiated whenever it is invoked.

In NetCore you define your DI inside Startup.cs on ConfigureServices method. Now, let’s see how you can define this.

Singleton:

services.AddSingleton<Interface, ImplementationClass>();

Scoped:

services.AddScoped<Interface, ImplementationClass>();

Transient:

services.AddTransient<Interface, ImplementationClass>();

You can read more about this pattern on:

https://martinfowler.com/articles/injection.html

If you have any doubt don’t hesitate to leave your comments or asking me ​​via Twitter.

💖 💪 🙅 🚩
jpblancodb
JPBlancoDB

Posted on November 9, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Dependency Injection in NetCore
netcore Dependency Injection in NetCore

November 9, 2019