1

I have the following Code.

public class TypeA : InterfaceA
{
    private ILogger _logger;
    public TypeA(ILogger logger)
    {
        _logger = logger;
    }
}

public class Main
{
    ...
    var loggerFactory = new LoggerFactory();
    ILogger<TypeA> typeALogger = _loggerFactory.CreateLogger<TypeA>();
    var typeAObj = new TypeA(typeALogger);
    ...
}

I want to use autofac to create the instance of TypeA like so:

// Autofac is configured ...

using var scope = container.BeginLifetimeScope();
var typeAObj = scope.Resolve<InterfaceA>();

How can I do this, but using the ILogger<TypeA> Logger from the existing LoggerFactory, as argument for the constructor?

Cellcon
  • 1,245
  • 2
  • 11
  • 27

2 Answers2

1

If you want to reuse the existing Microsoft logging infrastructure you can reuse the build-in DI setup via AutofacRegistration.Populate from Autofac.Extensions.DependencyInjection (a bit of docs):

public class TypeA : InterfaceA
{
    private ILogger _logger;
    public TypeA(ILogger<TypeA> logger)
    {
        _logger = logger;
    }
}

And registration:

var builder = new ContainerBuilder();

// setup logging infrastructure via build-in DI
IServiceCollection services = new ServiceCollection();
services.AddLogging(loggingBuilder => {}); 

// pass the setup to the Autofac
builder.Populate(services);
        
builder.RegisterType<TypeA>().As<InterfaceA>();
  
// use it      
var container = builder.Build();
using var scope = container.BeginLifetimeScope();
var typeAObj = scope.Resolve<InterfaceA>();
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • I am not completely sure, if this is what I had in mind. I need to find some time for checking it and will definitively come back and let you know. Anyway, thanks in advance for your answer! – Cellcon Apr 05 '23 at 21:17
0

You could use autofac's RegisterGeneric.

    var builder = new ContainerBuilder();

    builder.RegisterGeneric(typeof(Logger<>))
        .As(typeof(ILogger<>));

You'll need an instance of ILogger, so use ILoggerFactory to create it:

    builder.Register<ILoggerFactory>(context =>
        LoggerFactory.Create(builder =>
            builder.AddConsole()
        )
    ).SingleInstance();
thewallrus
  • 645
  • 4
  • 8