简体   繁体   中英

How do I pass a dependency to a Serilog Enricher?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM