Author : MD TAREQ HASSAN | Updated : 2021/05/29

What Is Dependency Injection?

Simple Console App

Nuget Package

Install-Package Microsoft.Extensions.DependencyInjection

Services/IFoo.cs

namespace ConsoleApp.Simple.Services
{
    public interface IFoo
    {
        int GetRandomNumber(int start = 1, int end = 10);
    }
}

Services/Foo.cs

using System;

namespace ConsoleApp.Simple.Services
{
    public class Foo : IFoo
    {
        public int GetRandomNumber(int start, int end)
        {
            return new Random().Next(start, end);
        }
    }
}

EntryPoint.cs

using ConsoleApp.Simple.Services;
using System;
using static System.Diagnostics.Debug;

namespace ConsoleApp.Simple
{
    public class EntryPoint
    {
		private IFoo _foo;
		public EntryPoint(IFoo foo)
		{
			_foo = foo;
		}

		public void Run(String[] args)
		{

			WriteLine("\n\n\n\n\n");
			WriteLine("=====================================================================================\n\n");

			WriteLine("DI in console app is working...\n");

			var randomNumber = _foo.GetRandomNumber();
			WriteLine($"Foo.GetRandomNumber(): {randomNumber}");

			WriteLine("\n\n=================================================================================");
			WriteLine("\n\n\n\n\n");

			Console.Read();
		}
	}
}

Startup.cs

using System;
using ConsoleApp.Simple.Services;
using Microsoft.Extensions.DependencyInjection;

namespace ConsoleApp.Simple
{
	public static class Startup
	{
		public static IServiceCollection ConfigureServices()
		{
			var serviceCollection = new ServiceCollection();

			serviceCollection.AddScoped<IFoo, Foo>();

			serviceCollection.AddTransient<EntryPoint>();

			return serviceCollection;
		}
	}
}

Program.cs

using Microsoft.Extensions.DependencyInjection;

namespace ConsoleApp.Simple
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.WriteLine("Hello World!");

            var services = Startup.ConfigureServices();
            var serviceProvider = services.BuildServiceProvider();

            serviceProvider.GetService<EntryPoint>().Run(args);
        }
    }
}

Using Generic Host Builder

Worker Service