Search code examples
c#.netdependency-injectionautofacilogger

How to Register ILogger(Microsoft.Extensions.Logging) with DI usinq autofac .net framework


I use ILogger from Microsoft.Extensions.Logging in a .net framework project. Now I want to register the ILogger in the container but i cant.All the answers are about .net core. i try

var builder = new ContainerBuilder();

builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

//first try
builder.RegisterGeneric(typeof(Logger<>)).As(typeof(ILogger<>));
IServiceCollection services = new ServiceCollection();

//second try
services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
IContainer container = builder.Build();

httpConfig.DependencyResolver = new AutofacWebApiDependencyResolver(container);

also my class is

public class TestController : ApiController
{
    private readonly ILogger<TestController > _logger;
    private readonly IService _service;

    public TestController (IService service, ILogger<TestController > logger)
        {
            _service = service;
            _logger = logger;
        }
}

The di is correct because other services have injected correct. When i include the logger in constructor i get the message An error occurred when trying to create a controller of type 'TestController '. Make sure that the controller has a parameterless public constructor.


Solution

  • Since trying to integraten with those extensions, consider populating the service collection is expected and populating the builder once everything is registered,

    Example from docs

    var builder = new ContainerBuilder();
    
    builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
    
    IServiceCollection services = new ServiceCollection();
    
    // The Microsoft.Extensions.Logging package provides this one-liner
    // to add logging services.
    services.AddLogging();
    
    // Once you've registered everything in the ServiceCollection, call
    // Populate to bring those registrations into Autofac. This is
    // just like a foreach over the list of things in the collection
    // to add them to Autofac.
    builder.Populate(services);
    
    IContainer container = builder.Build();
    
    httpConfig.DependencyResolver = new AutofacWebApiDependencyResolver(container);
    

    Reference Autofac: .Net Core Integration