More

    Easy methods to use keyed providers in ASP.NET Core

    on

    |

    views

    and

    comments

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

    Notice how the FileLogger, DatabaseLoggerand EventLogger providers are registered utilizing the keys "file", "database"and "occasion"respectively.

    Inject the keyed logger providers

    We will use the (FromKeyedServices) attribute to inject a particular 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("occasion")) ICustomLogger logger) =>
    {
        logger.Log("This textual content is recorded within the occasion system.");
        return Outcomes.Okay("Occasion logger executed efficiently.");
    });
    

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

    Share this
    Tags

    Must-read

    Google disputes false claims of large Gmail knowledge breach

    Google was as soon as once more pressured to announce that it had not suffered an information breach after quite a...

    Azul, Forged AI be a part of forces on Java efficiency

    Azul Programs has partnered with cloud utility efficiency firm Forged AI in an effort to enhance Java runtime efficiency, scale back the reminiscence and...

    DroneShield and SRI Group Educate Airports on Counter-UAV Tech

    DroneShield has launched a strategic partnership with SRI Group to deal with the escalating menace of drone incursions at airports worldwide. This collaboration brings...
    spot_img

    Recent articles

    More like this

    LEAVE A REPLY

    Please enter your comment!
    Please enter your name here