pengweiqhca / Xunit.DependencyInjection

Use Microsoft.Extensions.DependencyInjection to resolve xUnit test cases.
MIT License
366 stars 49 forks source link

Minimal hosting model / WebApplicationBuilder #109

Closed glen-84 closed 9 months ago

glen-84 commented 9 months ago

Is it possible to use the minimal hosting model?

I don't have a good understanding of how this all fits together, but I'd like to reuse some extension methods on WebApplicationBuilder for configuration purposes.

I tried something like this:

public class Startup
{
    public IHostBuilder CreateHostBuilder()
    {
        var builder = WebApplication.CreateSlimBuilder(
            new WebApplicationOptions()
            {
                EnvironmentName = "Testing"
            });

        builder.ConfigureSomething(); // Use an existing extension method.

        return builder.Host;
    }
}

... but I get:

The application name changed from "testhost" to "Api.Modules.UnitTests". Changing the host configuration using WebApplicationBuilder.Host is not supported. Use WebApplication.CreateBuilder(WebApplicationOptions) instead.

Is there some way to make this work?

pengweiqhca commented 9 months ago

WebApplication should used in asp.net core startup rather test startup.

glen-84 commented 9 months ago

Yes, I am using it in my ASP.NET Core Startup (Program.cs) file.

For the ASP.NET project, I have a bunch of extension methods like:

public static WebApplicationBuilder ConfigureAuthentication(this WebApplicationBuilder builder)
{
    if (builder.Environment.IsTesting())
    {
        builder.Services.AddAuthentication();
    }
    else
    {
        static void configureOptions(JwtBearerOptions options)
        {
            options.TokenValidationParameters.ClockSkew = TimeSpan.FromSeconds(5);
        }

        builder.Services
            .AddAuthentication(builder.Configuration.GetRequiredSection("Authentication")
                .GetValue<string>("DefaultScheme") ?? "UserJwts")
            .AddJwtBearer("UserJwts", configureOptions);
    }

    return builder;
}

... to configure various libraries.

I wanted to reuse these methods where it made sense. If there's no clean way to do this, then I may have to refactor these methods to instead extend IServiceCollection, and take things like the environment and configuration as method arguments.

pengweiqhca commented 9 months ago

May be this?

glen-84 commented 9 months ago

That's not really what I was asking about, although it might be useful if I try to use the MinimalApiHostBuilderFactory approach.

The name MinimalApiHostBuilderFactory seems a bit confusing – does it do anything specific to minimal APIs, or could it be used for other project types like MVC etc. that also use a Program.cs file?

Anyway, I might try using MinimalApiHostBuilderFactory later, and if that doesn't work for my project, I'll consider refactoring my configuration methods to extend IServiceCollection.

Thanks.