Search code examples
c#asp.net-coredependency-injectionasp.net-core-2.0autofac

Register ASP.NET Core ILogger<> from built-in logging mechanism to Autofac


I have a ASP.NET Core app using Autofac as DI container. I'm also using built-in logging mechanism that provides ILogger<> dependency. Now I'd like to register it in Autofac. How?


Solution

  • As already stated, when you use the official autofac-integration for asp.net-core you don't need to do anything. If you still want to do it manually, which is legit, you could do the following in the ConfigureContainer method.

    public void ConfigureContainer(ContainerBuilder builder)
    {
       // ... more registrations
       builder.RegisterInstance(new LoggerFactory())
                    .As<ILoggerFactory>();
    
       builder.RegisterGeneric(typeof(Logger<>))
              .As(typeof(ILogger<>))
              .SingleInstance();
    }
    

    Keep in mind that their is no specific logging-provider added.