问题
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