Prism Unity Register NLog as Microsoft.Extension.Logging.ILogger<T>

267 Views Asked by At

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.

2

There are 2 best solutions below

1
Franz On BEST ANSWER

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"/>
0
Rolf Kristensen On

Using AddNLog from NLog.Extensions.Logging-nuget-package with help from Prism.Microsoft.DependencyInjection.Extensions. By updating App.xaml.cs like this:

public partial class App : PrismApplication 
{
    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.RegisterServices(services =>
        {
            services.AddLogging(logging =>
            {
                logging.ClearProviders();
                logging.AddNLog();
            });
        });
    } 
} 

Then a window can acquire Microsoft.Extension.Logging.ILogger using dependency injection like this:

public partial class MainWindow : Window
{
    private readonly ILogger<MainWindow> _logger;
 
    public MainWindow(ILogger<MainWindow> logger)
    {
        InitializeComponent();
        _logger = logger;
    }
 
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        _logger.LogDebug("Hello");
    }
}