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>
This commit is contained in:
Stef HeyenrathandCopilot Autofix powered by AI authored and GitHub committed 2026-11-07 13:10:21 +01:00
1 parent f594a7cb19
commit 2760ecbe00
3 files changed
+164 -49

No files matched your search

+23 -1
View File
@@ -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
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
@@ -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<KestrelServerOptions>(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<Microsoft.Extensions.Hosting.IHostLifetime, NoopHostLifetime>();
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<IMappingMatcher, MappingMatcher>();
services.AddSingleton<IRandomizerDoubleBetween0And1, RandomizerDoubleBetween0And1>();
services.AddSingleton<IOwinRequestMapper, OwinRequestMapper>();
services.AddSingleton<IOwinResponseMapper, OwinResponseMapper>();
services.AddSingleton<IGuidUtils, GuidUtils>();
services.AddSingleton<IDateTimeUtils, DateTimeUtils>();
services.AddSingleton<IResponseMessageBuilder, ResponseMessageBuilder>();
services.AddSingleton<LogEntryMapper>();
services.AddSingleton<IWireMockMiddlewareLogger, WireMockMiddlewareLogger>();
#if NET8_0_OR_GREATER
AddCors(services);
#endif
_wireMockMiddlewareOptions.AdditionalServiceRegistration?.Invoke(services);
})
.Configure(appBuilder =>
{
appBuilder.UseMiddleware<GlobalExceptionMiddleware>();
#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<WireMockMiddleware>();
_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<IMappingMatcher, MappingMatcher>();
services.AddSingleton<IRandomizerDoubleBetween0And1, RandomizerDoubleBetween0And1>();
services.AddSingleton<IOwinRequestMapper, OwinRequestMapper>();
services.AddSingleton<IOwinResponseMapper, OwinResponseMapper>();
services.AddSingleton<IGuidUtils, GuidUtils>();
services.AddSingleton<IDateTimeUtils, DateTimeUtils>();
services.AddSingleton<IResponseMessageBuilder, ResponseMessageBuilder>();
services.AddSingleton<LogEntryMapper>();
services.AddSingleton<IWireMockMiddlewareLogger, WireMockMiddlewareLogger>();
#if NET8_0_OR_GREATER
AddCors(services);
#endif
_wireMockMiddlewareOptions.AdditionalServiceRegistration?.Invoke(services);
}
private void ConfigureApplication(IApplicationBuilder appBuilder)
{
appBuilder.UseMiddleware<GlobalExceptionMiddleware>();
#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<WireMockMiddleware>();
_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<Microsoft.AspNetCore.Hosting.Server.IServer>()
.Features
.Get<Microsoft.AspNetCore.Hosting.Server.Features.IServerAddressesFeature>()!
.Addresses
.ToArray();
#else
var addresses = _host.ServerFeatures
.Get<Microsoft.AspNetCore.Hosting.Server.Features.IServerAddressesFeature>()!
.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)
{
+36 -7
View File
@@ -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
}
}
}