Search code examples
c#asp.net-mvcdependency-injectionautofacautofac-configuration

How to Resolve ILogger in Autofac container


I am trying to replace dryIOC container with autofac container for some reason but I don't know the exact syntax how could I resolve ILogger uisng autofac

Here is how I register ILogger in DryIoc

public void Load(IContainer container)
{
    container.Register<ILoggerFactory, Log4NetLoggerFactory>();
    
    ConfigureLogger(container);
}

[Localizable(false)]
private void ConfigureLogger(IContainer container)
{
    container.Register<ILogger>(
        made: Made.Of(
            r => typeof(ILoggerFactory).GetMethod(nameof(ILoggerFactory.Create), new[] {          typeof(Type) }),
            factoryInfo: ServiceInfo.Of<ILoggerFactory>(),
            parameters: Parameters.Of.Name("type", r => r.Parent?.ImplementationType ?? typeof(Startup))),
        reuse: Reuse.Transient);
}

I have tried something like this, but it does not work with Autofac

container.Register<ILoggerFactory, Log4NetLoggerFactory>();


Solution

  • If you try to resolve an instance of Microsoft.Extensions.Logging.ILogger then you have two options:

    Option #1 - Resolve a ILogger<TCategoryName>.

    public class Something
    {
        private readonly ILogger logger;
    
        public Something(ILogger<Something> logger)
        {
            this.logger = logger;
        }
    }
    

    Option #2 - Resolve an ILogger instead of ILogger<TCategoryName> automatically.

    My nuget package does exactly this using Autofac:
    EgonsoftHU.Extensions.Logging.Autofac

    It contains an Autofac module. Register it then magic will happen.

    public class Something
    {
        private readonly ILogger logger;
    
        public Something(ILogger logger)
        {
            this.logger = logger; // It will be an instance of ILogger<Something>.
        }
    }