'C# ASP.NET Core DI with logging
I'm looking for DI solution for the following problem. I'm writing a custom SeriLog sync that requires a dependency from my serviceprovider. I can't seem to figure out how to access my serviceprovider from services.AddLogging():
services.AddSingleton<ICosmosFactory, CosmosFactory>();
services.AddLogging((builder) =>
{
var logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.AzureCosmosDB(
client: sp.Client,
databaseName: "MyDb",
collectionName: "logging",
timeToLive: TimeSpan.FromDays(7)
)
.CreateLogger();
builder.AddSerilog(logger);
});
In this example, Serilogs Sync needs an instance of CosmosClient which is provided by CosmosFactory. The only way I can see to grab it is to do the following:
builder.Services.BuildServiceProvider()
This is not ideal as it could potentially create duplicates of my singleton services.
Solution 1:[1]
I have no idea if this is the best approach. But playing around with it. I found the best way is to inject a ILoggerFactory as a singleton and configure that instead.
services.AddSingleton<ILoggerFactory>(sp =>
{
var factory = new LoggerFactory();
var logger = new LoggerConfiguration();
Serilog.Events.LogEventLevel level = Serilog.Events.LogEventLevel.Debug;
logger.WriteTo.AzureCosmosDB(
client:((ICosmosFactory)sp.GetRequiredService(typeof(ICosmosFactory))).Client,
databaseName: "Diagnostics",
collectionName: "logging",
timeToLive: TimeSpan.FromDays(logTTL),
restrictedToMinimumLevel: level
);
return factory;
});
If someone has a better answer or a reason this isnt a good answer. Please let me know.
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 | Batman |
