Posts

Showing posts from December, 2020

.Net Core Dependency Injection - Quick Use Guide

Hi all, we all know now, .Net Core supports Dependency Injection (DI) out of the box. Ok, so let's see how to use it in this quick use guide. For test this out let's create 2 projects (give names as you like); Worker service project - I called it MailSender Class library - and I named this as MailManager Let's use the DI: 1. Create a class in MailManager  I created a class called MailConfigurator.cs Create a method called GetData inside that class. 2. Open the Program.cs of your Worker Service project. Then lets define the scope and register our dependency in the dependency container: public static IHostBuilder CreateHostBuilder(string[] args) =>             Host.CreateDefaultBuilder(args)                 .ConfigureServices((hostContext, services) =>                 {                     services.AddSingleton<MailConfigurator>();                     services.AddHostedService<Worker>();                 }); NOTE: There are 3 service lifetimes; Transient, Sco