如何将依赖项传递给Serilog Enricher? [英] How do I pass a dependency to a Serilog Enricher?

查看:120
本文介绍了如何将依赖项传递给Serilog Enricher?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用程序中使用Serilog进行日志记录。在配置记录器时,我的代码是这样的:

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

我想向我的 MySerilogEnricher 类,但是当我尝试时,出现此编译器错误:

I want to inject some dependencies into my MySerilogEnricher class, but when I try, I get this compiler error:


错误CS0310: SerilogEnricher必须是具有以下内容的非抽象类型一个
公共无参数构造函数,以便将其用作通用类型或方法
'LoggerEnrichmentConfiguration.With()'中的参数
'TEnricher'

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

我理解为什么会收到此错误,但是我看不到解决它的简单方法。理想情况下,应该有一个 WithInstance 调用,我可以这样使用:

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

有没有办法将依赖项传递给 MySerilogEnricher ?我也许可以在其中包含一个带有MySerilogEnricher的类,并将其依赖项传递给属性,但这似乎很麻烦。

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.

推荐答案

您可以使用 .With()方法,而无需使用泛型来传递扩展程序实例。因此,在您的示例中,将是:

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

这篇关于如何将依赖项传递给Serilog Enricher?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆