This repository has been archived by the owner on Nov 17, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 71
/
DefaultHttpClientFactory.cs
77 lines (63 loc) · 2.68 KB
/
DefaultHttpClientFactory.cs
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Net.Http;
using System.Threading;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace Microsoft.Extensions.Http
{
internal class DefaultHttpClientFactory : IHttpClientFactory
{
private readonly IServiceProvider _services;
private readonly IOptionsMonitor<HttpClientFactoryOptions> _optionsMonitor;
// Lazy, because we're using a subtle pattern here to ensure that only one instance of
// HttpMessageHandler is created for each name.
private readonly ConcurrentDictionary<string, Lazy<HttpMessageHandler>> _cache;
private readonly Func<string, Lazy<HttpMessageHandler>> _valueFactory;
public DefaultHttpClientFactory(
IServiceProvider services,
IOptionsMonitor<HttpClientFactoryOptions> optionsMonitor)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (optionsMonitor == null)
{
throw new ArgumentNullException(nameof(optionsMonitor));
}
_services = services;
_optionsMonitor = optionsMonitor;
// case-sensitive because named options is.
_cache = new ConcurrentDictionary<string, Lazy<HttpMessageHandler>>(StringComparer.Ordinal);
_valueFactory = (name) => new Lazy<HttpMessageHandler>(() => CreateHandler(name), LazyThreadSafetyMode.ExecutionAndPublication);
}
public HttpClient CreateClient(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
var handler = _cache.GetOrAdd(name, _valueFactory);
var client = new HttpClient(handler.Value, disposeHandler: false);
var options = _optionsMonitor.Get(name);
for (var i = 0; i < options.HttpClientActions.Count; i++)
{
options.HttpClientActions[i](client);
}
return client;
}
private HttpMessageHandler CreateHandler(string name)
{
var builder = _services.GetRequiredService<HttpMessageHandlerBuilder>();
var options = _optionsMonitor.Get(name);
for (var i = 0; i < options.HandlerBuilderActions.Count; i++)
{
options.HandlerBuilderActions[i](builder);
}
return builder.Build();
}
}
}