.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);

  1. Worker service project - I called it MailSender
  2. 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, Scoped and Singleton.

3. Use the injected class 
Go to the Worker.cs inside the Worker Service project. This is where I want to use the MailConfigurator. 

In the Worker.cs create a constroctor method and add MailConfigurator as a parameter.

public class Worker : BackgroundService
    {
        private MailConfigurator _mailConfigurator;

        public Worker(MailConfigurator mailConfigurator)
        {
            _mailConfigurator = mailConfigurator;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _mailConfigurator.GetData();
        }
    }

And I have used the MailConfigurator class to call the method GetData without creating any instences of the MailConfigurator class. We have used the dependency which we have registered and passed by the DI container.

 


Comments

Popular posts from this blog

Deploy Angular 8 app to Azure with Azure DevOps

Apache ActiveMQ 5 with .Net Core 3.1 and C#

Firebase with.Net Core and C#