Skip to content

Add WebApplicationFactory.CreateServer for use from built service collection #62782

@BrennanConroy

Description

@BrennanConroy

Background and Motivation

While moving MVC tests from WebHostBuilder to HostBuilder, I noticed a couple tests expecting CreateServer to be called but it wasn't because in the HostBuilder case we were constructing the TestServer instance after the HostBuilder was built.

So it seemed logical to add a new overload that let you create the TestServer instance after the host was built.

Proposed API

public partial class WebApplicationFactory<TEntryPoint> : IDisposable, IAsyncDisposable where TEntryPoint : class
{
     protected virtual TestServer CreateServer(IWebHostBuilder builder) => new(builder);

+    protected virtual TestServer CreateServer(IServiceProvider serviceProvider) => new(serviceProvider);
}

Usage Examples

public class TestServerFactory<TStartup> : WebApplicationFactory<TStartup>
    where TStartup : class
{
    // other methods ...

    protected override TestServer CreateServer(IServiceProvider serviceProvider)
    {
        // potentially custom configuration
        return new(serviceProvider);
    }
}

Alternative Designs

Risks

Two CreateServer overloads now exist. So old test code would need to update to use the new overload now/as well.

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-ready-for-reviewAPI is ready for formal API review - https://github.com/dotnet/apireviewsarea-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templates

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions