Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

The answer is incredibly simple:

public async Task Invoke(HttpContext httpContext, MyLoggingService logger = null)
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda