2

I have a project that utilizes a 3rd party software which uses Serilog. For that purpose I added the following to my Startup method in Startup.cs file.

Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Verbose()
            .ReadFrom.ConfigurationSection(Configuration.GetSection("Logging:Serilog"))
        .CreateLogger(); 

On a separate project, I have service layer that uses a logging mechanism based on Microsoft.Extensions.Logging.ILogger.

Now I am adding UI to my initial project and I am injecting Microsoft.Extensions.Logging.ILogger to my controller classes through Service Collection; which I will then use (inside controllers) to create service layer objects.

The challange is; I would like to inject the existing Serilog logger into these controllers. Couldn't find a neat way of adding it to my service collection so that the controllers can fetch through DI. Any suggestions?

onur
  • 31
  • 1
  • 4

1 Answers1

2

The solution is to register an instance of your already-existing Logger object in your Dependency Injection container. Then this single instance will be passed to the constructor of your controller, instead of a new instance being created each time.

The code to do this will depend on the specific Dependency Injection framework you are using, but in Unity, it would be

   container.RegisterInstance<ILogger>(Log.Logger)

This should go after the code you posted, in which you instantiate Log.Logger.

You can additionally make your code more reusable by defining your own ILogger interface, as described in this answer, so that your controllers are not tied to the Serilog.ILogger interface.

Community
  • 1
  • 1
Sam Magura
  • 850
  • 8
  • 18