From 2760ecbe000d999b1585b5723aa2b03ddeecfe70 Mon Sep 17 00:00:00 2001 From: Stef Heyenrath Date: Sat, 7 Nov 2026 13:10:21 +0100 Subject: [PATCH] Switch to IHost for .NET 10 + update dotnet-WireMock (#1532) * Switch to IHost for .NET 10 * 'dotnet-WireMock stops on CTRL-C' * Potential fix for pull request finding 'Missing Dispose call on local IDisposable' Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> * . --------- Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 24 ++- .../Owin/AspNetCoreSelfHost.cs | 146 +++++++++++++----- src/dotnet-WireMock.Net/Program.cs | 43 +++++- 3 files changed, 164 insertions(+), 49 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index af18e62b..9062665f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -95,4 +95,26 @@ jobs: # run: dotnet test --project './test/WireMock.Net.Aspire.Tests/WireMock.Net.Aspire.Tests.csproj' -c Release --framework net8.0 - name: 'WireMock.Net.Aspire.Tests (net10.0)' - run: dotnet test --project './test/WireMock.Net.Aspire.Tests/WireMock.Net.Aspire.Tests.csproj' -c Release --framework net10.0 \ No newline at end of file + run: dotnet test --project './test/WireMock.Net.Aspire.Tests/WireMock.Net.Aspire.Tests.csproj' -c Release --framework net10.0 + + - name: 'dotnet-WireMock stops on CTRL-C' + run: | + set -m # job control, so the background process does not ignore SIGINT + dotnet build ./src/dotnet-WireMock.Net/dotnet-WireMock.csproj -c Release + dotnet ./src/dotnet-WireMock.Net/bin/Release/net10.0/dotnet-WireMock.dll --Urls http://localhost:0 > wiremock.log 2>&1 & # port 0 = OS assigns a free port + PID=$! + sleep 3 + grep -q 'Server listening at' wiremock.log || { cat wiremock.log; kill -9 $PID; exit 1; } + kill -INT $PID + for i in $(seq 1 10); do + if ! kill -0 $PID 2>/dev/null; then + EXIT_CODE=0 + wait $PID || EXIT_CODE=$? + echo "dotnet-WireMock stopped (exit code $EXIT_CODE)" + exit $EXIT_CODE + fi + sleep 1 + done + echo "dotnet-WireMock did not stop within 10 seconds after CTRL-C" + kill -9 $PID + exit 1 diff --git a/src/WireMock.Net.Minimal/Owin/AspNetCoreSelfHost.cs b/src/WireMock.Net.Minimal/Owin/AspNetCoreSelfHost.cs index e0bb0fdc..bb9ed9f7 100644 --- a/src/WireMock.Net.Minimal/Owin/AspNetCoreSelfHost.cs +++ b/src/WireMock.Net.Minimal/Owin/AspNetCoreSelfHost.cs @@ -11,6 +11,11 @@ using WireMock.Serialization; using WireMock.Services; using WireMock.Util; +#if NET10_0 +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Microsoft.Extensions.Configuration; +#endif + namespace WireMock.Owin; internal partial class AspNetCoreSelfHost @@ -20,7 +25,11 @@ internal partial class AspNetCoreSelfHost private readonly IWireMockLogger _logger; private readonly HostUrlOptions _urlOptions; +#if NET10_0 + private Microsoft.Extensions.Hosting.IHost _host = null!; +#else private IWebHost _host = null!; +#endif public bool IsStarted { get; private set; } @@ -43,6 +52,36 @@ internal partial class AspNetCoreSelfHost public Task StartAsync() { +#if NET10_0 + var builder = WebApplication.CreateBuilder(new WebApplicationOptions + { + // Workaround for https://github.com/wiremock/WireMock.Net/issues/292 + // On some platforms, AppContext.BaseDirectory is null, which causes WebHostBuilder to fail if ContentRoot is not + // specified (even though we don't actually use that base path mechanism, since we have our own way of configuring + // a filesystem handler). + ContentRootPath = string.IsNullOrEmpty(AppContext.BaseDirectory) ? Directory.GetCurrentDirectory() : null + }); + + builder.Configuration.Sources.Clear(); + builder.Configuration.AddEnvironmentVariables(); + builder.Logging.ClearProviders(); + builder.Logging.AddProvider(new WireMockAspNetCoreLoggerProvider(_logger)); + builder.Logging.SetMinimumLevel(LogLevel.Warning); + builder.Services.Configure(builder.Configuration.GetSection("Kestrel")); + + // The default ConsoleLifetime cancels Ctrl+C and shuts down the host itself, which prevents the consuming application from controlling the process lifetime. + builder.Services.AddSingleton(); + ConfigureServices(builder.Services); + builder.WebHost.ConfigureKestrel(options => + { + SetKestrelOptionsLimits(options); + SetHttpsAndUrls(options, _wireMockMiddlewareOptions, _urlOptions.GetDetails()); + }); + + var app = builder.Build(); + ConfigureApplication(app); + _host = app; +#else var builder = new WebHostBuilder(); // Workaround for https://github.com/wiremock/WireMock.Net/issues/292 @@ -63,58 +102,71 @@ internal partial class AspNetCoreSelfHost logging.AddProvider(new WireMockAspNetCoreLoggerProvider(_logger)); logging.SetMinimumLevel(LogLevel.Warning); }) - .ConfigureServices(services => - { - services.AddSingleton(_wireMockMiddlewareOptions); - services.AddSingleton(_wireMockMiddlewareOptions.AdminPaths); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - -#if NET8_0_OR_GREATER - AddCors(services); -#endif - _wireMockMiddlewareOptions.AdditionalServiceRegistration?.Invoke(services); - }) - .Configure(appBuilder => - { - appBuilder.UseMiddleware(); - -#if NET8_0_OR_GREATER - UseCors(appBuilder); - - var webSocketOptions = new WebSocketOptions(); - if (_wireMockMiddlewareOptions.WebSocketSettings?.KeepAliveIntervalSeconds != null) - { - webSocketOptions.KeepAliveInterval = TimeSpan.FromSeconds(_wireMockMiddlewareOptions.WebSocketSettings.KeepAliveIntervalSeconds); - } - - appBuilder.UseWebSockets(webSocketOptions); -#endif - _wireMockMiddlewareOptions.PreWireMockMiddlewareInit?.Invoke(appBuilder); - - appBuilder.UseMiddleware(); - - _wireMockMiddlewareOptions.PostWireMockMiddlewareInit?.Invoke(appBuilder); - }) + .ConfigureServices(ConfigureServices) + .Configure(ConfigureApplication) .UseKestrel(options => { SetKestrelOptionsLimits(options); - SetHttpsAndUrls(options, _wireMockMiddlewareOptions, _urlOptions.GetDetails()); }) .ConfigureKestrelServerOptions() .Build(); +#endif return RunHost(_cts.Token); } + #if NET10_0 + private sealed class NoopHostLifetime : Microsoft.Extensions.Hosting.IHostLifetime + { + public Task WaitForStartAsync(CancellationToken cancellationToken) => Task.CompletedTask; + + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; + } +#endif + + private void ConfigureServices(IServiceCollection services) + { + services.AddSingleton(_wireMockMiddlewareOptions); + services.AddSingleton(_wireMockMiddlewareOptions.AdminPaths); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + +#if NET8_0_OR_GREATER + AddCors(services); +#endif + _wireMockMiddlewareOptions.AdditionalServiceRegistration?.Invoke(services); + } + + private void ConfigureApplication(IApplicationBuilder appBuilder) + { + appBuilder.UseMiddleware(); + +#if NET8_0_OR_GREATER + UseCors(appBuilder); + + var webSocketOptions = new WebSocketOptions(); + if (_wireMockMiddlewareOptions.WebSocketSettings?.KeepAliveIntervalSeconds != null) + { + webSocketOptions.KeepAliveInterval = TimeSpan.FromSeconds(_wireMockMiddlewareOptions.WebSocketSettings.KeepAliveIntervalSeconds); + } + + appBuilder.UseWebSockets(webSocketOptions); +#endif + _wireMockMiddlewareOptions.PreWireMockMiddlewareInit?.Invoke(appBuilder); + + appBuilder.UseMiddleware(); + + _wireMockMiddlewareOptions.PostWireMockMiddlewareInit?.Invoke(appBuilder); + } + private Task RunHost(CancellationToken token) { try @@ -126,10 +178,18 @@ internal partial class AspNetCoreSelfHost #endif appLifetime.ApplicationStarted.Register(() => { +#if NET10_0 + var addresses = _host.Services.GetRequiredService() + .Features + .Get()! + .Addresses + .ToArray(); +#else var addresses = _host.ServerFeatures .Get()! .Addresses .ToArray(); +#endif if (_urlOptions.Urls == null) { @@ -177,7 +237,11 @@ internal partial class AspNetCoreSelfHost _logger.Info("Server using .NET Standard 2.0"); #endif +#if NET10_0 + return Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(_host, token); +#else return _host.RunAsync(token); +#endif } catch (Exception ex) { diff --git a/src/dotnet-WireMock.Net/Program.cs b/src/dotnet-WireMock.Net/Program.cs index 69cb172a..3c3bedfb 100644 --- a/src/dotnet-WireMock.Net/Program.cs +++ b/src/dotnet-WireMock.Net/Program.cs @@ -1,7 +1,5 @@ // Copyright © WireMock.Net -using System; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using WireMock.Logging; using WireMock.Net.StandAlone; @@ -25,6 +23,7 @@ public class Program private static readonly IWireMockLogger Logger = new WireMockLogger(XLogger); private static WireMockServer _server = null!; + private static int _stopped; static async Task Main(string[] args) { @@ -33,29 +32,59 @@ public class Program return; } + using var cancelationTokenSource = new CancellationTokenSource(); + Logger.Info("Press Ctrl+C to shut down"); Console.CancelKeyPress += (s, e) => { - Stop("CancelKeyPress"); + // Prevent the runtime from terminating the process (exit code 130 / -1073741510) + // Main stops the server and returns normally. + e.Cancel = true; + Logger.Info("Shutdown requested because 'CancelKeyPress'"); + cancelationTokenSource.Cancel(); }; System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += ctx => { - Stop("AssemblyLoadContext.Default.Unloading"); + Stop("AssemblyLoadContext.Default.Unloading", cancelationTokenSource); }; - while (true) + while (!cancelationTokenSource.IsCancellationRequested) { Logger.Info("Server running : {0}", _server.IsStarted); - await Task.Delay(SleepTime).ConfigureAwait(false); + + try + { + await Task.Delay(SleepTime, cancelationTokenSource.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + // Shutdown requested + } } + + Stop("shutdown requested", cancelationTokenSource); } - private static void Stop(string why) + private static void Stop(string why, CancellationTokenSource cancellationTokenSource) { + if (Interlocked.Exchange(ref _stopped, 1) == 1) + { + return; + } + Logger.Info("Server stopping because '{0}'", why); _server.Stop(); Logger.Info("Server stopped"); + + try + { + cancellationTokenSource.Cancel(); + } + catch (ObjectDisposedException) + { + // Main already finished + } } } \ No newline at end of file