dotnet / dotnet/aspnetcore

WebApplication.CreateBuilder() should allow a configure action parameter for testing purposes

Open
#62,594 0 comments 0 reactions 0 assignees View on GitHub
api-suggestion area-mvc feature-mvc-testing
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

## Background and Motivation

`WebApplicationBuilder` has several _internal_ constructors that take the `configureDefaults` action, like `internal WebApplicationBuilder(WebApplicationOptions options, Action? configureDefaults = null)`.

The `configureDefaults` action seems to be used internally for testing purposes:

```
// This is for testing purposes
configureDefaults?.Invoke(bootstrapHostBuilder);
```

However, I am unable to configure the builder for my testing purposes. For example, see my comment in [Issue 55867](https://github.com/dotnet/aspnetcore/issues/55867#issuecomment-3046941805). To work around that issue, I needed to insert a `WebHostDefaults.StaticWebAssetsKey` into `IConfiguration` to specify a custom Static Web Assets manifest to allow testing on WSL2 (see [StaticWebAssetsLoader.ResolveManifest](https://github.com/dotnet/aspnetcore/blob/main/src/Hosting/Hosting/src/StaticWebAssets/StaticWebAssetsLoader.cs) for more details). There is no supported way to do it before `WebApplication.CreateBuilder(WebApplicationOptions)` is called, and it's too late after. I had to resort to reflection to call the internal `WebApplicationBuilder` constructor.

The public `configureDefaults` action could also be useful in production.

## Proposed API

Please add the following methods to the `WebApplication` class.

```
public static WebApplicationBuilder CreateBuilder(WebApplicationOptions options, Action? configureDefaults) =>
new(options, configureDefaults);
public static WebApplicationBuilder CreateSlimBuilder(WebApplicationOptions options, Action? configureDefaults) =>
new(options, slim: true, configureDefaults);
public static WebApplicationBuilder CreateEmptyBuilder(WebApplicationOptions options, Action? configureDefaults) =>
new(options, slim: false, empty: true, configureDefaults);

```

That's all what's needed.

## Alternative Designs

There is no alternative.

## Risks

There is no risk.

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.