具有依赖注入的布局渲染器不起作用

问题描述 投票:0回答:1

我已经按照https://github.com/NLog/NLog/wiki/How-to-write-a-custom-layout-renderer文章创建了一个布局渲染器。 hello-world示例可以找到,但是当我去它注入的东西时,它没有写任何东西。

  1. 我删除了构造函数注入,并且日志记录按预期工作。
  2. 我已经将相同的项目注入到控制器的构造函数中并且可以正常工作。
// NOTE: ICorrelationContextAccessor is part of the CorrelationId nuget package
[LayoutRenderer("correlation-id")]
public class CorrelationIdLayoutRenderer : LayoutRenderer
{
    private readonly ICorrelationContextAccessor _correlationContext;

    public CorrelationIdLayoutRenderer(ICorrelationContextAccessor correlationContext)
    {
        _correlationContext = correlationContext;
    }

    protected override void Append(StringBuilder builder, LogEventInfo logEvent)
    {
        var correlation = _correlationContext.CorrelationContext.CorrelationId;

        builder.Append(correlation);
    }
}

nlog.config

<extensions>
    <add assembly="NLog.Web.AspNetCore"/>
    <add assembly="[[ My assembly is here]]"/>
</extensions>
<targets>
 <target xsi:type="File" name="ownFile-web" fileName="[[PATH]]/nlog-own-${shortdate}.log"
                layout="${longdate}|${level:fixedLength=True:padding=5:padCharacter= :upperCase=True}|${correlation-id}|${message} ${exception:format=tostring}" />
</targets>

我希望相关性能够实现。

c# dependency-injection nlog
1个回答
1
投票

您需要覆盖NLog中的CreateInstance,因此它可以创建CorrelationIdLayoutRenderer

ConfigurationItemFactory.Default.CreateInstance = (Type type) =>
{ 
    // your custom target.
    if(type == typeof(CorrelationIdLayoutRenderer))
      return new CorrelationIdLayoutRenderer(...); // TODO get ICorrelationContextAccessor 
    else
      return Activator.CreateInstance(type); //default
};

更新:

如果您注册太晚,您可以按如下方式对NLog重新加载所有程序集进行排队:

ConfigurationItemFactory.Default = null; // (namespace NLog.Config).

它将在首次使用NLog之前重新加载

© www.soinside.com 2019 - 2024. All rights reserved.