具有.net核心的NLog的具有注入服务的自定义目标 [英] Custom target with injected services for NLog with .net core

查看:72
本文介绍了具有.net核心的NLog的具有注入服务的自定义目标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将NLog和NLog.Extensions.Logging一起用于aps.net核心支持.我需要创建一个自定义目标并将服务注入到目标的构造函数中.
以下代码永远不会执行:

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) {....}

我删除IService参数后,一切正常.

as soon as I remove IService param, everything works.

如何将我的服务注入自定义目标?

How can I inject my service into custom target?

推荐答案

仍然不确定如何正确地做到这一点.现在可以通过以下方式实现(不是很好的解决方案,但至少可以奏效):

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");
    .......
}  

它尝试使用开箱即用的NLog提供程序(用于默认目标和布局渲染)解析对象,如果失败(尝试使用IService解析我的目标时),则使用asp.net核心DI进行解析.

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.

这篇关于具有.net核心的NLog的具有注入服务的自定义目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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