In .Net 5 and previous, we used to have a startup.cs file, with ConfigureServices and Configure Method inside. In below function I have added ILoggerManager as parameter of the function and then passed it to app.ConfigureExceptionHandler function.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerManager logger)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.ConfigureExceptionHandler(logger);
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
But with .Net 6 there is no startup.cs file and only program.cs file. There is no ConfigureService or Configure methods inside program.cs and all methods or functions are being called in a procedural way without any class or methods declaration like below:
var builder = WebApplication.CreateBuilder(args);
var logger = new LoggerManager();
builder.Services.AddControllers();
builder.Services.AddDbContext<DocumentDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DocumentStore")));
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<ILoggerManager, LoggerManager>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.ConfigureExceptionHandler(<how to pass dependency here>);
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
My question is how can I pass a dependency to app.ConfigureExceptionHandler() function in .Net 6. I could not find any documentation on it.
CodePudding user response:
Since you are creating LoggerManager
yourself (var logger = new LoggerManager();
) you can simply do:
app.ConfigureExceptionHandler(logger);
If you prefer to use the DI you can utilize IServiceProvider
exposed via WebApplication.Services
property:
var resolvedLoggerManager = app.Services.GetRequiredService<ILoggerManager>();
app.ConfigureExceptionHandler(resolvedLoggerManager);