1

I'm trying to use Serilog and Ninjet on a C# Windows client (forms) application using .Net 6.0

Can anyone tell me how I configure Ninject so that ILogger is injected here:

public partial class TestingForm : Form
{

private readonly ILogger<TestingForm> _logger;

TestingForm(ILogger<TestingForm> logger)
{ 
 _logger = logger;
}
//etc.

}

I was rather hoping to use something like the .UseSeriLog() used here:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .UseSerilog()
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

from https://www.ezzylearning.net/tutorial/logging-in-asp-net-core-5-using-serilog but I just can't work out how to do it with Ninject

spud
  • 495
  • 5
  • 10
  • Does Ninject support .NET 6? It doesn't look like it supported. .NET has its own dependency injection system. See here how to use DI with winforms: https://stackoverflow.com/questions/70475830/how-to-use-dependency-injection-in-winforms – thewallrus Nov 09 '22 at 16:01
  • Yes Ninject does support .NET 6. I have it configured and injecting successfully I just can't work out how to get Ninject to do what it needs to do to allow the code example above to work. I believe https://github.com/serilog/serilog-extensions-logging may help but the examples of how to configure it use the 'built-in' .NET dependency injection. – spud Nov 10 '22 at 14:46

1 Answers1

0

I created a Windows forms app targeting .NET 6. I installed Serilog and Ninject through Nuget.

MyModule.cs:

using Ninject.Modules;
using Serilog;

namespace WinFormsApp1;

public class MyModule : NinjectModule
{
    public override void Load()
    {
        Bind<ILogger>().To<SeriLogging>();
    }
}

Programs.cs:

internal static class Program
{
    [STAThread]
    static void Main()
    {
        ApplicationConfiguration.Initialize();
        var kernel = new StandardKernel(new MyModule());
        var form = kernel.Get<Form1>();
        Application.Run(form);
    }
}

Serilog.cs

public class SeriLogging : ILogger
{
    public void Write(LogEvent logEvent)
    {
        //Implement Serilog here
    }
}

Serilog's ILogger is non-generic so just use ILogger. If you want ILogger of type TestingForm then you probably need to install Microsoft.Extensions.Logging.

using Serilog;

namespace WinFormsApp1;

public partial class Form1 : Form
{
    private readonly ILogger _logger;

    public Form1(ILogger logger)
    {
        InitializeComponent();
        _logger = logger;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        _logger.Error("aaaah");
    }
}
thewallrus
  • 645
  • 4
  • 8