[英]C# ASP.NET Core DI with logging
I'm looking for DI solution for the following problem.我正在为以下问题寻找 DI 解决方案。 I'm writing a custom SeriLog sync that requires a dependency from my serviceprovider.我正在编写一个自定义 SeriLog 同步,它需要我的服务提供商的依赖。 I can't seem to figure out how to access my serviceprovider from services.AddLogging()
:我似乎无法弄清楚如何从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.在此示例中,Serilogs Sync 需要 CosmosFactory 提供的 CosmosClient 实例。 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.这并不理想,因为它可能会创建我的 singleton 服务的副本。
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.我发现最好的方法是将 ILoggerFactory 作为 singleton 注入并配置它。
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.请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.