mirror of
https://github.com/wiremock/WireMock.Net.git
synced 2026-03-31 22:53:27 +02:00
Add method CreateHttpClientFactory (#1325)
* Add method CreateHttpClientFactory * rev
This commit is contained in:
18
src/WireMock.Net.Minimal/Http/WireMockHttpClientFactory.cs
Normal file
18
src/WireMock.Net.Minimal/Http/WireMockHttpClientFactory.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
// Copyright © WireMock.Net
|
||||
#if NET5_0_OR_GREATER
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
using WireMock.Server;
|
||||
|
||||
namespace WireMock.Http;
|
||||
|
||||
internal class WireMockHttpClientFactory(WireMockServer server, params DelegatingHandler[] handlers) : IHttpClientFactory
|
||||
{
|
||||
private readonly Lazy<HttpClient> _lazyHttpClient = new(() => server.CreateClient());
|
||||
|
||||
public HttpClient CreateClient(string name)
|
||||
{
|
||||
return handlers.Length > 0 ? server.CreateClient(handlers) : _lazyHttpClient.Value;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -120,6 +120,32 @@ public partial class WireMockServer : IWireMockServer
|
||||
#endregion
|
||||
|
||||
#region HttpClient
|
||||
#if NET5_0_OR_GREATER
|
||||
private readonly Lazy<IHttpClientFactory> _lazyHttpClientFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Create a <see cref="IHttpClientFactory"/> which can be used to generate a HttpClient to call this instance.
|
||||
/// <param name="handlers">
|
||||
/// An ordered list of System.Net.Http.DelegatingHandler instances to be invoked
|
||||
/// as an System.Net.Http.HttpRequestMessage travels from the System.Net.Http.HttpClient
|
||||
/// to the network and an System.Net.Http.HttpResponseMessage travels from the network
|
||||
/// back to System.Net.Http.HttpClient. The handlers are invoked in a top-down fashion.
|
||||
/// That is, the first entry is invoked first for an outbound request message but
|
||||
/// last for an inbound response message.
|
||||
/// </param>
|
||||
/// </summary>
|
||||
[PublicAPI]
|
||||
public IHttpClientFactory CreateHttpClientFactory(params DelegatingHandler[] handlers)
|
||||
{
|
||||
if (!IsStarted)
|
||||
{
|
||||
throw new InvalidOperationException("Unable to create IHttpClientFactory because the service is not started.");
|
||||
}
|
||||
|
||||
return handlers.Length > 0 ? new WireMockHttpClientFactory(this, handlers) : _lazyHttpClientFactory.Value;
|
||||
}
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// Create a <see cref="HttpClient"/> which can be used to call this instance.
|
||||
/// <param name="handlers">
|
||||
@@ -427,6 +453,10 @@ public partial class WireMockServer : IWireMockServer
|
||||
}
|
||||
|
||||
InitSettings(settings);
|
||||
|
||||
#if NET5_0_OR_GREATER
|
||||
_lazyHttpClientFactory = new Lazy<IHttpClientFactory>(() => new WireMockHttpClientFactory(this));
|
||||
#endif
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IWireMockServer.Stop" />
|
||||
|
||||
Reference in New Issue
Block a user