Custom target with injected services for NLog with .net core

随声附和 提交于 2019-12-12 13:07:04

问题


I'm using NLog with NLog.Extensions.Logging for aps.net core support. I need to create a custom target and inject service into the target's constructor.
The following code never gets executed:

public MyTarget(IService service) {....}

as soon as I remove IService param, everything works.

How can I inject my service into custom target?


回答1:


Still not sure what is the right and proper way how to do that. For now implemented in a following way (not a good solution, but at least it works):

public void ConfigureServices(IServiceCollection services)
{
    ......
   services.AddScoped<MyCustomNlogTarget>();
}

public void Configure(IApplicationBuilder app, 
                    IHostingEnvironment env, 
                    ILoggerFactory loggerFactory,
                    IServiceProvider provider)
{
    var nlogProvider = ConfigurationItemFactory.Default.CreateInstance;
    ConfigurationItemFactory.Default.CreateInstance = type =>
    {
        try
        {
            return nlogProvider(type);
        }
        catch (Exception)
        {
        }

        return provider.GetService(type);
    };

    loggerFactory.AddNLog();
    env.ConfigureNLog("NLog.config");
    .......
}  

It tries to resolve the object using out of the box NLog provider (for default targets and layout renders), if it fails (when trying to resolve my target with IService), it resolves using asp.net core DI.



来源:https://stackoverflow.com/questions/40377283/custom-target-with-injected-services-for-nlog-with-net-core

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