Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
ASP.NET Core 5 - How to have optional dependencies?

I'm developing a middleware which I would like to have an optional dependency on a internal logging library. In another words, if MyLoggingService is registered, great!, else, life goes on and ill log to console.

But by declaring public async Task Invoke(HttpContext httpContext, MyLoggingService logger), I get a runtime error saying that it was not registred. I tried setting a default value to null but that didn't work. Also, because its a middleware, I can't overload the Invoke method.

Is there a solution other than requesting the service collection and resolving the dependency myself?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Instead of making dependencies optional, consider:

  • Programming to an abstraction, e.g. IMyLoggingService
  • Register a Null Object implementation

For instance:

public class CustomMiddleware1 : IMiddleware
{
    private readonly IMyLoggingService logger;

    public CustomMiddleware1(IMyLoggingService logger) => this.logger = logger;

    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        this.logger.Log("Before");

        await next(context);

        this.logger.Log("After");
    }
}

Null Object implementation:

public sealed class NullMyLoggingService : IMyLoggingService
{
    public void Log(LogEntry e) { }
}

Registrations:

services.AddSingleton<IMyLoggingService>(new NullMyLoggingService());

app.Use<CustomMiddleware1>();

The call to AddSingleton<IMyLoggingService>(new NullMyLoggingService()) ensures a registration for IMyLoggingService always exists. This prevents complexity in consumers, who would otherwise have to add conditional logic for the case that the logger isn't present.

This null implementation can be replaced by simply adding a second IMyLoggingService after the first:

services.AddScoped<IMyLoggingService, DbMyLoggingService>();

app.Use<CustomMiddleware1>();
over 4 years ago · Santiago Trujillo Report

0

The answer is incredibly simple:

public async Task Invoke(HttpContext httpContext, MyLoggingService logger = null)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!