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

118
Visualizações
Determine the target type for a dependency during resolution

It seems to be impossible to determine the type for which a dependency is resolved:

containerBuilder.Register(context =>
{
   // What is the type for which this component is resolved?
   var type = default(Type); // TBD
   return context.Resolve<ILoggerFactory>().CreateLogger(type);
});

The goal here is to create the .NET Core logger with the right category for the type that it is applied to.

The example in the Autofac documentation describes how to pull this off with a Middleware component, and I was successful. But it seems adding a pipeline to every registration has performance implications, and I've yet to discover a way to only apply the pipeline to registrations for components that have a dependency on ILogger.

Motivation: the obvious choice seems to be to change the dependency to be of type ILogger<T> where T is the type on which this dependency is applied, like so:

public class Component
{
    public Component(ILogger<Component> logger)...
}

but experience tells me a lot of developers hastily copy and paste components and forget to change the type parameter, resulting in confusing logs. In the current code, where we still use Common.Logging, our component would simply need a non-generic ILog:

public class Component
{
    public Component(ILog log)...
}

In our previous DI container, Castle.Windsor, it would be as easy as this:

public class LoggerSubDependencyResolver : ISubDependencyResolver
{
    public bool CanResolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
    {
        return dependency.TargetType == typeof(ILog);
    }

    public object Resolve(CreationContext context, ISubDependencyResolver contextHandlerResolver, ComponentModel model, DependencyModel dependency)
    {
        return CanResolve(context, contextHandlerResolver, model, dependency) ? LogManager.GetLogger(model.Implementation) : null;
    }
}

Is there an easier way to accomplish this? Or this is the way to do it and I'm overly concerned about the performance implications?

over 4 years ago · Santiago Trujillo
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