0

I have a shared Code between my backend and my frontend(WPF), where be backend currently uses NReco.Logging.File which is compatible with Microsoft.Extensions.Logging.ILogger. But in the fronend, I use NLog. Now I want to provide a NLog.Logger, every time when a ILogger is requested using Constructor. Therefore I need to find a solution to setup the Prism.DI accordingly.

Currently I found the NLog.Extension.Hosting and NLog.Extensions.Logging, which registers NLog for Microsoft.Extension.Hosting. https://github.com/NLog/NLog.Extensions.Logging/tree/master Additionally I found the following Entry, for registering Serilog as ILog Provider: Resolve generic Microsoft.Extensions.Logging.ILogger<T> with Unity - get InvalidCastException

Is there any way to register NLog to Prism Unity to provide as Microsoft.Extension.Logging.ILogger.

Franz
  • 358
  • 6
  • 18
  • can you expand on what exactly is the problem? the [answer](https://stackoverflow.com/a/70828207/5758420) you linked looks like it should work out of the box with NLog.Extensions.Logging – Haukinger Aug 28 '23 at 11:22
  • Yes, it works, but only when using Microsoft.Extension.Hosting as DI, but my Prism WPF Application uses the Unity DI. Therefore the Extensions don't fit. – Franz Aug 28 '23 at 12:22
  • My target is as already described above, that I want to setup Unity to return a NLog.Logger when a class requests one using constructor – Franz Aug 28 '23 at 12:24
  • What error are you getting, with what code? – Andy Aug 28 '23 at 13:00
  • you're aware that the extension you linked is an extension for the unity container? – Haukinger Aug 28 '23 at 13:11
  • If you mean the 2nd, that a Extension for Microsoft.Extension.Hosting, as far as I see. – Franz Aug 28 '23 at 14:08
  • And yes the Link to the Questing on Stackoverflow, is using Unity, but it is using Serilog instead of NLog, this was the problem. – Franz Aug 28 '23 at 14:11

1 Answers1

1

After checking the whole answer of the the other questing again, I could solve the problem the following way.

public static IContainerRegistry AddLogger(this IContainerRegistry services)
{
    var loggerFactory = new NLogLoggerFactory();
    var provider = new NLogLoggerProvider();
    loggerFactory.AddProvider(provider);
    services.RegisterInstance<ILoggerFactory>(loggerFactory);
    services.Register(typeof(ILogger<>), typeof(Logger<>));
    return services;
}

So now, all request go for ILogger are resolved with NLogger.

    <PackageReference Include="NLog.Extensions.Logging" Version="5.3.3"/>
Franz
  • 358
  • 6
  • 18
  • 1
    Excellent choice to use `Microsoft.Extensions.Logging.ILogger`, and then just setup NLog as Logging-provider. Notice the `NLogLoggerFactory` default-constructor initializes itself with a default-provider, so no need to create `NLogLoggerProvider` and call `AddProvider`. – Rolf Kristensen Aug 28 '23 at 16:12