DependencyInjection using IServiceCollection and IServiceProvider in .NET Core


using System;
using Microsoft.Extensions.DependencyInjection;
namespace DesignPattern
{

#nullable enable
public class Demo
{
public static void Main()
{

        bool isDependencyInjected = true;
        if (isDependencyInjected)
        {  //This way we are going to inject dependencies via Microsoft Dependency injection container
            var collection = new ServiceCollection();
            collection.AddScoped<IDB, DB>();
            collection.AddScoped<IBiz, Biz>();
            var provider = collection.BuildServiceProvider();

            var db = provider.GetService<IDB>();
            var biz = provider.GetService<IBiz>();
            var _ui = new UI(biz);
        }
        else
        {
            var _ui = new UI(new Biz(new DB()));

            _ui.CallBizAndSave("technoMan", "assowdro");
        }
        Console.WriteLine("Data persisted");
        Console.WriteLine("Press any key to exit");
        Console.ReadLine();
    }
}

public class UI
{
    private IBiz _biz;
        public UI(IBiz bz )
    {
            _biz = bz;
    }
   public  void CallBizAndSave(string name, string pwd)
    {
        //var biz = new Biz();
        _biz.CallDBandPersist(name, pwd);
    }
}

public class Biz : IBiz
{
    private IDB _db;
    public Biz(IDB db )
    {
        _db = db;
    }
    public void CallDBandPersist(string name, string pwd)
    {
       
        _db.PersistToDB(name, pwd);

    }

}

public class DB : IDB
{
    public void PersistToDB(string name, string pwd)
    {
        // save and chill
    }
}

public interface IBiz
{
    void CallDBandPersist(string name, string pwd);
}

public interface IDB
{
    void PersistToDB(string name, string pwd);
}

}