dotnet / dotnet/aspnetcore

Add a way to customize WebApplicationBuilder before Build is called

Open
#44,599 9 comments 2 reactions 0 assignees View on GitHub
api-suggestion area-minimal
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 5h
Merged PRs (30d)
276

Description

## Background and Motivation

Before the Minimal API there was [`IStartupFilter`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.hosting.istartupfilter?view=aspnetcore-6.0) interface that allowed us to customize existing `IApplicationBuilder`. But I can't find something similar for `WebApplicationBuilder`.

It would be really useful to have such an option. For example, `WebApplicationBuilder.Logging` immediately executes provided code, so it is impossible to use configuration sources or other services that can be added later.

As I found, Serilog developers faced the same issue [here](https://github.com/serilog/serilog-aspnetcore/blob/bf4ae072f7472d285c72f9a43f3eb4920e743110/src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs#L100): instead of simple calling `WebApplicationBuilder.Logging.AddProvider` they have to do lazy initialization via `ConfigureServices.AddSingleton(SerilogFactory)` and moreover implement their own `ILoggerFactory` for that.

Same thoughts may be also applied for `WebApplication`.

## Proposed API

Add startup filters for `WebApplicationBuilder` and `WebApplication`:

```csharp
public interface IWebApplicationBuilderStartupFilter
{
Action Configure(Action next);
}

public interface IWebApplicationStartupFilter
{
Action Configure(Action next);
}
```

## Usage Examples

```csharp
public class WebApplicationBuilderStartupFilter : IWebApplicationBuilderStartupFilter
{
public Action Configure(Action next)
{
return builder =>
{
var someRequiredColdLogSettings = builder.Configuration.Get();

builder.Logging.AddProvider(new MyLoggerProvider(someRequiredColdLogSettings));

next(builder);
};
}
}
```

## Alternative Designs

Instead of some startup filters there may be some pre build/run actions.

## Risks

I'm not an expert of AspNetCore, so if there is another way to solve my issue please tell me.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.