Keyed Services Dependency Injection :- Keyed Services Dependency Injection is a Software Design Pattern introduced in .Net 8 with some enhancements
in existing Dependency Injection. Exiting Dependency Injection system has some limitations for services registration and multiple implementation for same Interface. for example if you have a Interface and you want to provide multiple implementation for the Interface then it has few limitations in that case , so
implementing the multiple implementation for same interface with a Key is a new concept in Keyed Services dependency injection system. These Keys can be
a String, Enum or any integer value or any value that is uniquikly indentified in system.
By using Keyed Services Dependency Injection in application we can make our code more managable and readble and it provides better testability to application
components.
With Keyed Services Dependency Injection we can easily enables the future changes and applied it in very easy way without more modifications of existing code.
ASP.Net core has a built-in support for Keyed Serives Dependency Injections in .Net 8.
As its name suggest ,it injects the object of a class to outside that class and used in into a dependent class using three types of dependency techniques that is listed below.
Below are some Implementation Guidlines for Keyed Services Dependency Injection to use into the application that we need to follow.
Practical Implementation for Keyed Services Dependency Injection :- For implementing the Keyed Services Dependency Injection in application firstly I have create a Interface in which i have declare a common method FileTransferLocation() and it is returning the string message.So before creation of
As shown in below code I have created a Interface named it IFileTransfer that you can find into below code snippet.
public interface IFileTransfer
{
public string FileTransferLocation();
}
After creating a Interface now I have created two services inside the Services folder, first service is SFTPTransferClass Class and it implements the IFileTransfer Interface into it and provides the implementation of FileTransferLocation() Method into this class and second service is S3BucketTransferClass and it implements the IFileTransfer Interface into it and provides the implementation of FileTransferLocation() Method into this class.
public class SFTPTransferClass : IFileTransfer
{
public string FileTransferLocation()
{
return "SFTP Transfer Class";
}
}
public class S3BucketTransferClass : IFileTransfer
{
public string FileTransferLocation()
{
return "S3 Bucket Transfer Class";
}
}
After creating the Service Classes and Interface we have to register this services into the Program.cs file with any one of the Service Life time methods(like AddKeyedScoped,AddKeyedSingleton,AddKeyedTransient) with Interface and Service class using Key name as depicted into the below code example.
using KeyedServicesDI.Interfaces;
using KeyedServicesDI.Services;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddKeyedScoped("SFTPClass");
builder.Services.AddKeyedScoped("S3BucketClass");
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Now we have to use our dependency object into the Client Class or Controller using the below code.
using System.Diagnostics;
namespace KeyedServicesDI.Controllers
{
public class HomeController : Controller
{
private readonly ILogger _logger;
public HomeController(ILogger logger)
{
_logger = logger;
}
public IActionResult Index([FromKeyedServices("SFTPClass")] IFileTransfer fileTransfer)
{
string msg = fileTransfer.FileTransferLocation();
ViewBag.MessageSFTP = msg;
return View();
}
public IActionResult Privacy([FromKeyedServices("S3BucketClass")] IFileTransfer fileTransfer)
{
string msg = fileTransfer.FileTransferLocation();
ViewBag.MessageS3Bucket = msg;
return View();
}
}
Below is some screen images that I have attached for your reference and with these images you can easily understand the steps that we required for implementing the Dependency Injection and example code also. Make sure to use .Net 8 only. Below is the image for Solution Explorer after adding the folders and required class files and make sure to choose framework version is .Net 8.
Image of Program.cs file using the AddKeyedScoped services.
Image of Controller Class having Constructor Dependency code.
About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the
applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server,
EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.