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.
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.