12

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.

user2023861
  • 8,030
  • 9
  • 57
  • 86

1 Answers1

6

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();
rmc00
  • 877
  • 10
  • 20
  • 8
    But what if my dependency is not a singleton, let's say it's a service registered in the container with scoped or transient lifetime? – Radu Popovici - Oncica Dec 05 '17 at 07:54
  • In that specific example, I think you would need Serilog to be integrated with your DI container. For example, Serilog has an integration with Autofac: https://github.com/nblumhardt/autofac-serilog-integration – rmc00 Dec 06 '17 at 17:53
  • 1
    Does that even work? The documentation for autofac-serilog-integration suggest that it enables contextual ILogger instances to be resolved using Serilog, it does not suggest that this will cause Serilog to attempt to resolve all its own dependencies from Autofac. – Neutrino Oct 29 '19 at 10:30