问题
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?
回答1:
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>();
来源:https://stackoverflow.com/questions/45774780/inject-a-dependency-in-a-serilog-enricher-with-autofac