HomeCloud ComputingThe right way to use keyed companies in ASP.NET Core

The right way to use keyed companies in ASP.NET Core



var builder = WebApplication.CreateBuilder(args);
// Register a number of keyed companies for the ICustomLogger interface
builder.Providers.AddKeyedScoped("file");
builder.Providers.AddKeyedScoped("database");
builder.Providers.AddKeyedScoped("occasion");
var app = builder.Construct();

Observe how the FileLogger, DatabaseLogger, and EventLogger companies are registered utilizing the keys "file", "database", and "occasion", respectively.

Inject the keyed logger companies

We will use the [FromKeyedServices] attribute to inject a selected implementation of our logger service in our minimal API endpoints as proven within the code snippet given under.

app.MapGet("/customlogger/file", ([FromKeyedServices("file")] ICustomLogger fileLogger) =>
{
    fileLogger.Log("This textual content is written to the file system.");
    return Outcomes.Okay("File logger executed efficiently.");
});
app.MapGet("/customlogger/db", ([FromKeyedServices("database")] ICustomLogger databaseLogger) =>
{
    databaseLogger.Log("This textual content is saved within the database.");
    return Outcomes.Okay("Database logger executed efficiently.");
});
app.MapGet("/customlogger/occasion", ([FromKeyedServices("event")] ICustomLogger logger) =>
{
    logger.Log("This textual content is recorded within the occasion system.");
    return Outcomes.Okay("Occasion logger executed efficiently.");
});

Thus, through the use of DI and keyed companies, we are able to implement every of our logger companies as soon as, then merely ask for the proper kind of the logger after we want one with out having to make use of a manufacturing unit to instantate the logger. And at any time when we need to swap the implementations—from FileLogger to DatabaseLogger, for instance—all we have to do is change the configuration we specied whereas registering the companies with the container. The DI system will plug in the proper logger mechanically at run time.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments