I'm using Serilog in my application for logging. When I'm configuring the logger, I have code like this:
var log = new LoggerConfiguration()
.Enrich.With<MySerilogEnricher>()
.ReadAppSettings()
.CreateLogger();
I want to inject some dependencies into my MySerilogEnricher
class, but when I try, I get this compiler error:
error CS0310: 'SerilogEnricher' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TEnricher' in the generic type or method 'LoggerEnrichmentConfiguration.With()'
I understand why I'm getting this error, but I don't see an easy way around it. Ideally, there'd be a WithInstance
call that I could use like this:
var instance = new MySerilogEnricher(myDependency);
var log = new LoggerConfiguration()
.Enrich.WithInstance<MySerilogEnricher>(instance)
.ReadAppSettings()
.CreateLogger();
Is there any way to pass a dependency to MySerilogEnricher
? I could maybe have a class with MySerilogEnricher in it and pass the dependency to it in a property, but that seems messy.
You can use the .With()
method without the generic to pass an instance of your enricher. So in your example, it would be:
var instance = new MySerilogEnricher(myDependency);
var log = new LoggerConfiguration()
.Enrich.With(instance)
.ReadAppSettings()
.CreateLogger();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With