Serilog with Autofac

I created a nuget-package with an extensions method for AutoFac's ContainerBuilder.

All you need to do is install it and call the extension with either a logger-configuration or a log-path (and optional a template, you get a default).

var builder = new ContainerBuilder();
builder.RegisterSerilog("my-log-path"); // or a loggerconfiguration
var container = builder.Build();
var logger = container.Resolve<ILogger<MyClass>>();
logger.LogInformation("Hello World");

This also works perfectly with ASP.NET-Core. You find samples and the source-code on the github-repository.


There is another Nuget package for Autofac and Serilog integration here: Autofac-Serilog integration

It works well with ASP.NET Core 3.1. Steps:

  1. Install package
  2. Create the logger as normal
  3. Call builder.RegisterLogger() in one of the module or in the ConfigureContainer() method of the Startup.cs file

Maybe this helps:

builder.Register<ILogger>((c, p) =>
{
    return new LoggerConfiguration()
      .WriteTo.RollingFile(
        AppDomain.CurrentDomain.GetData("DataDirectory").ToString() + "/Log-{Date}.txt")
      .CreateLogger();
}).SingleInstance();