Inject a dependency in a SeriLog enricher with autofac

£可爱£侵袭症+ 提交于 2021-02-20 19:05:38

问题


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

This is my container setup:

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

While the enricher would look something like

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?


回答1:


When you enrich With<T> all it's doing, literally, is calling new T().

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


来源:https://stackoverflow.com/questions/45774780/inject-a-dependency-in-a-serilog-enricher-with-autofac

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!