'How to resolve dependency in serilog custom sink?

I have multi tenant system and I need to log in different database based on tenant id. i have created custom sink but I'm not able to resolve my dependencies in custom sink class

CustomLogSink.cs :

public class CustomLogSink : ILogEventSink
    {
        public CustomLogSink(IWorkSpaceProvider provider)
        {

        }
        public void Emit(LogEvent logEvent)
        {
            
        }
    }

Program.cs :

 public class Program
    {
        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                            .MinimumLevel.Information()
                            .CreateLogger();


            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            return Host.CreateDefaultBuilder(args)
                        .UseSerilog((context, cfg) =>
                        {
                            cfg.WriteTo.Sink(new CustomLogSink());
                        })
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.UseStartup<Startup>();
                    });
        }
    }

How can i resolve my dependencies in CustomLogSink.cs ?



Solution 1:[1]

You need to add the CustomLogSink to injection model like this :

services.AddTransient<ILogEventSink, CustomLogSink>();

This sink will be auto loaded by Serilog and you do not need the WriteTo. Do however mind possible circular ref like I got here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Banshee