.NET Core Dependency Injection - One Interface, Multiple Implementations

In this article, we will see how we can inject the dependency when we have more than one implementation for an interface.

Consider a scenario where you want to get shopping cart object and you have implemented IShoppingCart Interface. Now, you have multiple options to get the shopping cart like from Database, API, or Cache. Here, we need to implement all these three as concrete implementations for an interface, IShoppingCart. Now, the question is how we can decide which instance is to be instantiated as generally we see one implementation for one interface and add it into service collection for dependency injection. So, let’s see the implementation step by step.

Open Visual Studio and create a new project.

Select the API as the template and click OK.

Create an IShoppingcart Interface having GetCart method.
  1. namespace MultipleImplementation  
  2. {  
  3.     public interface IShoppingCart  
  4.     {  
  5.         object GetCart();  
  6.     }  
  7. }  

Implement the GetCart method of IShoppingCart interface in ShoppingCartCache.

  1. namespace MultipleImplementation  
  2. {  
  3.     public class ShoppingCartCache : IShoppingCart  
  4.     {  
  5.         public object GetCart()  
  6.         {  
  7.             return "Cart loaded from cache.";  
  8.         }  
  9.     }  
  10. }  

Implement the same interface in ShoppingCartDB.

  1. namespace MultipleImplementation  
  2. {  
  3.     public class ShoppingCartDB : IShoppingCart  
  4.     {  
  5.         public object GetCart()  
  6.         {  
  7.             return "Cart loaded from DB";  
  8.         }  
  9.     }  
  10. }  

At last, implement the same interface in ShoppingCartAPI.

  1. namespace MultipleImplementation  
  2. {  
  3.     public class ShoppingCartAPI : IShoppingCart  
  4.     {  
  5.         public object GetCart()  
  6.         {  
  7.             return "Cart loaded through API.";  
  8.         }  
  9.     }  
  10. }  

Now, we need a repository which will internally decide which implementation should be instantiated and called to get the GetCart method from it. So, create IShoppingCartRepository having the GetCart method.

  1. namespace MultipleImplementation  
  2. {  
  3.     public interface IShoppingCartRepository  
  4.     {  
  5.         object GetCart();  
  6.     }  
  7. }  

Create an enum to select the concrete implementation type, i.e, Cache, DB, or API.

  1. namespace MultipleImplementation  
  2. {  
  3.     public class Constants  
  4.     {  
  5.     }  
  6.   
  7.     public enum CartSource  
  8.     {  
  9.         Cache=1,  
  10.         DB=2,  
  11.         API=3  
  12.     }  
  13. }  

In the implementation of IShoppingCartRepository, we use constructor injection and we take Func delegate as a parameter. Func delegate expects a string as parameter and IShoppingCart as a return value. So in the GetCart method, you can see that we are using an enum to pass the parameter value which indicates the type of implementation we want to instantiate.

  1. using System;  
  2.   
  3. namespace MultipleImplementation  
  4. {  
  5.     public class ShoppingCartRepository : IShoppingCartRepository  
  6.     {  
  7.         private readonly Func<string, IShoppingCart> shoppingCart;  
  8.         public ShoppingCartRepository(Func<string, IShoppingCart> shoppingCart)  
  9.         {  
  10.             this.shoppingCart = shoppingCart;  
  11.         }  
  12.   
  13.         public object GetCart()  
  14.         {  
  15.             return shoppingCart(CartSource.DB.ToString()).GetCart();  
  16.         }  
  17.     }  
  18. }  

In the same way, we need to add Func in startup class. First, we add the concrete implementation in service collection and on each request based on the parameter value, we used to get that concrete class.

  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.Extensions.Configuration;  
  4. using Microsoft.Extensions.DependencyInjection;  
  5. using System;  
  6.   
  7. namespace MultipleImplementation  
  8. {  
  9.     public class Startup  
  10.     {  
  11.         public Startup(IConfiguration configuration)  
  12.         {  
  13.             Configuration = configuration;  
  14.         }  
  15.   
  16.         public IConfiguration Configuration { get; }  
  17.   
  18.         public void ConfigureServices(IServiceCollection services)  
  19.         {  
  20.   
  21.             services.AddScoped<IShoppingCartRepository, ShoppingCartRepository>();  
  22.   
  23.             services.AddSingleton<ShoppingCartCache>();  
  24.             services.AddSingleton<ShoppingCartDB>();  
  25.             services.AddSingleton<ShoppingCartAPI>();  
  26.   
  27.             services.AddTransient<Func<string, IShoppingCart>>(serviceProvider => key =>  
  28.             {  
  29.                 switch (key)  
  30.                 {  
  31.                     case "API":  
  32.                         return serviceProvider.GetService<ShoppingCartAPI>();  
  33.                     case "DB":  
  34.                         return serviceProvider.GetService<ShoppingCartDB>();  
  35.                     default:  
  36.                         return serviceProvider.GetService<ShoppingCartCache>();  
  37.                 }  
  38.             });  
  39.   
  40.             services.AddMvc();  
  41.         }  
  42.   
  43.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  44.         {  
  45.             if (env.IsDevelopment())  
  46.             {  
  47.                 app.UseDeveloperExceptionPage();  
  48.             }  
  49.   
  50.             app.UseMvc();  
  51.         }  
  52.     }  
  53. }  

You can download the sample from here.