4

I want to create a Serilog Enricher injecting some data from a dependency. How can autofac inject my dependency into an enricher?

This is my container setup:

builder.Register((c, p) =>
{
  return new LoggerConfiguration()
   .Enrich.FromLogContext()
   .Enrich.With<MyEnricherWhichCanAddMoreDataFromADependency>()
   // ...
  .CreateLogger();
}).As<ILogger>();

While the enricher would look something like

public class MyEnricherWhichCanAddMoreDataFromADependency : ILogEventEnricher
{
    public MyEnricherWhichCanAddMoreDataFromADependency(IDependency d) 
    { ... do stuff with the dependency ... }
}

Constructor injection does not seem to work. Or am I doing something wrong?

dampee
  • 3,392
  • 1
  • 21
  • 37

1 Answers1

5

When you enrich With<T> all it's doing, literally, is calling new T().

If you want to pass the enricher through DI you need to do that yourself.

builder.Register((c, p) =>
{
  var e = c.Resolve<MyEnricherWhichCanAddMoreDataFromADependency>();
  return new LoggerConfiguration()
   .Enrich.FromLogContext()
   .Enrich.With(e)
   // ...
  .CreateLogger();
}).As<ILogger>();
Travis Illig
  • 23,195
  • 2
  • 62
  • 85