Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

0

The answer is incredibly simple:

public async Task Invoke(HttpContext httpContext, MyLoggingService logger = null)
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda