Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public interface ITaxCalculator
{
int CalculateTax();
}
public class IndiaTaxCalculator : ITaxCalculator
{
public int CalculateTax() { return 30; }
}
public class UAETaxCalculator : ITaxCalculator
{
public int CalculateTax() { return 0; }
}
public enum Locations
{
India,
UAE,
USA
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public class Purchase
{
private readonly Func _accessor;
public Purchase(Func accessor)
{
_accessor = accessor;
}
public int CheckOut(Locations locations)
{
var countryTax = _accessor(locations);
var total = countryTax.CalculateTax() + 200;
return total;
}
}
}
// See https://aka.ms/new-console-template for more information
using ConsoleApp1;
using Microsoft.Extensions.DependencyInjection;
Console.WriteLine("Hello, World!");
Console.Clear();
//step 1
//ServiceCollection : IServiceCollection
var collection = new ServiceCollection();
//step 2 - register classes..
collection.AddScoped();
collection.AddScoped();
//step 3
collection.AddScoped>(
ServiceProvider => key =>
{
switch (key)
{
case Locations.India: return ServiceProvider.GetService();
case Locations.UAE: return ServiceProvider.GetService();
default: return null;
}
}
);
collection.AddScoped();
var provider = collection.BuildServiceProvider();
var purchase = provider.GetService();
var total =purchase?.CheckOut(Locations.UAE);
Console.WriteLine(total);