Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit f08f789

Browse files
committed
Make HttpUtils use lazy factories to prevent static init exceptions in Blazor
1 parent e7535a3 commit f08f789

File tree

1 file changed

+17
-6
lines changed

1 file changed

+17
-6
lines changed

src/ServiceStack.Text/HttpUtils.HttpClient.cs

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,14 @@ public static partial class HttpUtils
1919
private class HttpClientFactory
2020
{
2121
private readonly Lazy<HttpMessageHandler> lazyHandler;
22-
internal HttpClientFactory(HttpClientHandler handler) =>
23-
lazyHandler = new Lazy<HttpMessageHandler>(() => handler, LazyThreadSafetyMode.ExecutionAndPublication);
22+
internal HttpClientFactory(Func<HttpClientHandler> handler) =>
23+
lazyHandler = new Lazy<HttpMessageHandler>(() => handler(), LazyThreadSafetyMode.ExecutionAndPublication);
2424
public HttpClient CreateClient() => new(lazyHandler.Value, disposeHandler: false);
2525
}
2626

2727
// Ok to use HttpClientHandler which now uses SocketsHttpHandler
2828
// https://github.com/dotnet/runtime/blob/main/src/libraries/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs#L16
29-
public static HttpClientHandler HttpClientHandler { get; set; } = new() {
29+
public static Func<HttpClientHandler> HttpClientHandlerFactory { get; set; } = () => new() {
3030
UseDefaultCredentials = true,
3131
AutomaticDecompression = DecompressionMethods.Brotli | DecompressionMethods.Deflate | DecompressionMethods.GZip,
3232
};
@@ -38,10 +38,21 @@ internal HttpClientFactory(HttpClientHandler handler) =>
3838
// .Configure<HttpClientFactoryOptions>(options =>
3939
// options.HttpMessageHandlerBuilderActions.Add(builder => builder.PrimaryHandler = HandlerFactory))
4040
// .BuildServiceProvider().GetRequiredService<IHttpClientFactory>();
41-
41+
4242
// Escape & BYO IHttpClientFactory
43-
private static HttpClientFactory clientFactory = new(HttpClientHandler);
44-
public static Func<HttpClient> CreateClient { get; set; } = () => clientFactory.CreateClient();
43+
private static HttpClientFactory? clientFactory;
44+
public static Func<HttpClient> CreateClient { get; set; } = () => {
45+
try
46+
{
47+
clientFactory ??= new(HttpClientHandlerFactory);
48+
return clientFactory.CreateClient();
49+
}
50+
catch (Exception ex)
51+
{
52+
Tracer.Instance.WriteError(ex);
53+
return new HttpClient();
54+
}
55+
};
4556

4657
public static HttpClient Create() => CreateClient();
4758

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy