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.
2
Answers
Since you are creating
LoggerManager
yourself (var logger = new LoggerManager();
) you can simply do:If you prefer to use the DI you can utilize
IServiceProvider
exposed viaWebApplication.Services
property:For anyone trying obtain dependencies prior to calling
builder.Build()
(e.g. for use in services set-up), you can use an intermediate WebApplicationBuilder to build an additional WebApplication instance as below (Note that you cannot callbuilder.Build()
twice, hence the need for the intermediate builder).