DI .net core conditionally

				
					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<Locations, ITaxCalculator> _accessor;

        public Purchase(Func<Locations, ITaxCalculator> 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<IndiaTaxCalculator>();
collection.AddScoped<UAETaxCalculator>();

//step 3
collection.AddScoped<Func<Locations, ITaxCalculator>>(
    ServiceProvider => key =>
    {
        switch (key)
        {
            case Locations.India: return ServiceProvider.GetService<IndiaTaxCalculator>();
            case Locations.UAE: return ServiceProvider.GetService<UAETaxCalculator>();
            default: return null;
        }
    }
);

collection.AddScoped<Purchase>();

var provider = collection.BuildServiceProvider();

var purchase = provider.GetService<Purchase>();
var total =purchase?.CheckOut(Locations.UAE);
Console.WriteLine(total);

				
			

Leave a Comment