Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting logger into middleware dependency

I have a middleware library I intend on using in multiple projects. The middleware itself looks something like:

public SdkMiddleware(RequestDelegate next, ILogger<SdkMiddleware> logger, ISdk sdk)
{
   this.next = next;
   this.logger = logger;
   this.sdk = agentSdk;

   this.sdk.Init();
   ...
}

Thanks to DI, I can simply inject my logger:

// Would rather this class be internal...
public class Sdk: ISdk
{
    private ILogger<Sdk> logger;
    public Sdk(ILogger<Sdk> logger)
    {
        this.logger = logger;
    }

    public void Init() {
        this.logger.Info(...) // Do some logging
    }

The downside to this is my class needs to be registered in every ASP.Net project's Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<ISdk, Sdk>();

Is the best/only route? Every time I want to inject a logger into a class, I need to register that class for DI in my composition root?

like image 784
Mister Epic Avatar asked May 25 '26 02:05

Mister Epic


1 Answers

There is nothing wrong in having the consumer of your library compose the dependencies for this library in the composition root. That's how dependency injection works. You could of course provide some default implementations and a custom extension method that would register those default implementations into the DI and then let the consumer simply call your extension method.

like image 108
Darin Dimitrov Avatar answered May 26 '26 15:05

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!