-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResilientHttpClientFactory.cs
More file actions
52 lines (45 loc) · 1.91 KB
/
ResilientHttpClientFactory.cs
File metadata and controls
52 lines (45 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System;
using System.Collections.Concurrent;
using ResilientHttpClient.Core;
namespace ResilientHttpClient.Extensions.DependencyInjection
{
/// <summary>
/// Default implementation of IResilientHttpClientFactory that creates named clients.
/// </summary>
internal class ResilientHttpClientFactory : IResilientHttpClientFactory
{
private readonly ConcurrentDictionary<string, Func<IResilientHttpClient>> _clientFactories;
/// <summary>
/// Initializes a new instance of the <see cref="ResilientHttpClientFactory"/> class.
/// </summary>
public ResilientHttpClientFactory()
{
_clientFactories = new ConcurrentDictionary<string, Func<IResilientHttpClient>>(StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Registers a factory function for creating a named client.
/// </summary>
/// <param name="name">The name of the client.</param>
/// <param name="factory">A function that creates the client instance.</param>
internal void RegisterClient(string name, Func<IResilientHttpClient> factory)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException(nameof(name));
if (factory == null)
throw new ArgumentNullException(nameof(factory));
_clientFactories.TryAdd(name, factory);
}
/// <inheritdoc/>
public IResilientHttpClient CreateClient(string name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException(nameof(name));
if (!_clientFactories.TryGetValue(name, out var factory))
{
throw new ArgumentException($"No HTTP client registered with name '{name}'. " +
$"Available clients: {string.Join(", ", _clientFactories.Keys)}");
}
return factory();
}
}
}