本文介绍了使用autofac在SeriLog浓缩器中注入依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个 Serilog Enricher ,从依赖项中注入一些数据.autofac如何将我的依赖项注入浓缩器?

I want to create a Serilog Enricher injecting some data from a dependency. How can autofac inject my dependency into an enricher?

这是我的容器设置:

builder.Register((c, p) =>
{
  return new LoggerConfiguration()
   .Enrich.FromLogContext()
   .Enrich.With<MyEnricherWhichCanAddMoreDataFromADependency>()
   // ...
  .CreateLogger();
}).As<ILogger>();

浓缩器看起来像

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?

推荐答案

当您使用丰富时,实际上是正在调用 new T() .

如果要通过DI传递浓缩器,则需要自己进行.

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

这篇关于使用autofac在SeriLog浓缩器中注入依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-02 06:00