无法配置 Autofac 以将 Serilog 注入为 .NET 6 Web 应用程序中 ILogger 的实现

发布于 2025-01-18 19:56:38 字数 2366 浏览 0 评论 0原文

我正在努力通过 Autofac 在 .NET 6 Web 应用程序中将 Serilog 配置为 ILogger 的实现。

这是我到目前为止所拥有的......

var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json")
                                              .Build();

Log.Logger = new LoggerConfiguration().ReadFrom
                                      .Configuration(configuration)
                                      .CreateBootstrapLogger();

var builder = WebApplication.CreateBuilder(args)
                            .ConfigureKeyVaultAppConfiguration<Program>();

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Host
       .UseServiceProviderFactory(new AutofacServiceProviderFactory())
       .ConfigureContainer<ContainerBuilder>(containerBuilder =>
          {
             void RegisterModules()
             {
                 containerBuilder.RegisterModule<DataAccessModule>();
             }

             void RegisterConfigs()
             {
                 containerBuilder.RegisterAllConfigurationsInAssembly(typeof(PersistenceSettings).Assembly);
             }

             RegisterModules();
             RegisterConfigs();
         })
       .UseSerilog((ctx, lc) => lc.WriteTo.Console()
                                  .ReadFrom.Configuration(ctx.Configuration));

builder.Logging.ClearProviders();
builder.Logging.AddSerilog(Log.Logger);

var app = builder.Build();

app.UseSerilogRequestLogging();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

当我运行它时......

DependencyResolutionException:无法使用可用服务和参数调用类型“[My Class]”上的“Autofac.Core.Activators.Reflection.DefaultConstructorFinder”找到的任何构造函数:无法解析参数“Microsoft.Extensions.Logging”。构造函数“Void .ctor(Supertext.Language.Types.PersistenceSettings, Microsoft.Extensions.Logging.ILogger)'。

我可以看到很多其他开发人员也遇到同样的问题(ex.1, ex 2),但他们的解决方案尚未解决。我的问题。

I'm struggling to configure Serilog as the implementation for ILogger via Autofac in a .NET 6 web app.

Here's what I have so far...

var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json")
                                              .Build();

Log.Logger = new LoggerConfiguration().ReadFrom
                                      .Configuration(configuration)
                                      .CreateBootstrapLogger();

var builder = WebApplication.CreateBuilder(args)
                            .ConfigureKeyVaultAppConfiguration<Program>();

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Host
       .UseServiceProviderFactory(new AutofacServiceProviderFactory())
       .ConfigureContainer<ContainerBuilder>(containerBuilder =>
          {
             void RegisterModules()
             {
                 containerBuilder.RegisterModule<DataAccessModule>();
             }

             void RegisterConfigs()
             {
                 containerBuilder.RegisterAllConfigurationsInAssembly(typeof(PersistenceSettings).Assembly);
             }

             RegisterModules();
             RegisterConfigs();
         })
       .UseSerilog((ctx, lc) => lc.WriteTo.Console()
                                  .ReadFrom.Configuration(ctx.Configuration));

builder.Logging.ClearProviders();
builder.Logging.AddSerilog(Log.Logger);

var app = builder.Build();

app.UseSerilogRequestLogging();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

And when I run it...

DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type '[My Class]' can be invoked with the available services and parameters: Cannot resolve parameter 'Microsoft.Extensions.Logging.ILogger logger' of constructor 'Void .ctor(Supertext.Language.Types.PersistenceSettings, Microsoft.Extensions.Logging.ILogger)'.

I can see plenty of other devs with the same problem (ex. 1, ex. 2), but their solutions haven't solved my problem.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冷心人i 2025-01-25 19:56:38

确保您像 ILogger 一样注入 ILogger,而不仅仅是普通的旧 ILogger我认为没有配置可以注入非类型化记录器,因为记录器需要知道它们正在记录的类别(源类是什么)才能创建。 (这不是 Autofac 的事情,而是 .NET Core 日志记录的事情。)

如果出于某种原因需要提供字符串作为类别并手动获取 ILogger,则需要注入 ILoggerFactory 并从那里创建记录器。

Make sure you're injecting ILogger<T> like ILogger<MyClass> and not just plain old ILogger. I don't think there is configuration to inject an untyped logger because loggers need to know what category (what the source class is) that they're logging for in order to get created. (That's not an Autofac thing, that's a .NET Core logging thing.)

If you need to provide a string as a category for some reason and manually get just an ILogger, you need to inject ILoggerFactory and create the logger from there.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文