2

When working with Microsoft.Extensions.Logging, normally one registers an ILoggerfactory and map between the logger implementation and ILogger<>.

I was looking for a way to inject the non-generic ILogger and letting the IoC-Container (in this case Autofac) generate the typed ILogger<> with the class is getting injected to.

In this article https://blog.rsuter.com/logging-with-ilogger-recommendations-and-best-practices/ it is said:

Prefer injecting the ILogger interface and if necessary the ILogger<T> interface. Ideally, your class’ constructor requests an ILogger and the IoC framework creates an instance of an ILogger<T> where T is the requesting class.

And I agree with it, I would like to be able to inject just an ILogger and get the correct contextual instance.

The autofac serilog integration (https://github.com/nblumhardt/autofac-serilog-integration) does something like this but for Serilog.

This library configures Autofac to automatically configure the correct contextual logger for each class into which an ILogger is injected.

So is there a way to get this working with Autofac, SeriLog and Microsoft.Extensions.Logging?

I have tried a bit without a lot of effort.

Steven proposed something cool which I may get working by using the above autofac serilog integration and injecting the Serilog Logger into my custom abstraction, but this way I would lose the ability for structured logging, etc.

It would be nice if someone could give some guidance.

aminography
  • 21,986
  • 13
  • 70
  • 74
Rafa Gomez
  • 690
  • 8
  • 24

0 Answers0