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

117
Views
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
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!