Reputation: 3447
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?
Upvotes: 4
Views: 1713
Reputation: 23924
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>();
Upvotes: 5