forked from Azure/autorest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServiceClient.cs
234 lines (212 loc) · 8.59 KB
/
ServiceClient.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.Rest.TransientFaultHandling;
namespace Microsoft.Rest
{
/// <summary>
/// ServiceClient is the abstraction for accessing REST operations and their payload data types..
/// </summary>
/// <typeparam name="T">Type of the ServiceClient.</typeparam>
public abstract class ServiceClient<T> : IDisposable
where T : ServiceClient<T>
{
/// <summary>
/// Indicates whether the ServiceClient has been disposed.
/// </summary>
private bool _disposed;
/// <summary>
/// Reference to the first HTTP handler (which is the start of send HTTP
/// pipeline).
/// </summary>
protected HttpMessageHandler FirstMessageHandler { get; set; }
/// <summary>
/// Reference to the innermost HTTP handler (which is the end of send HTTP
/// pipeline).
/// </summary>
protected HttpClientHandler HttpClientHandler { get; set; }
/// <summary>
/// Initializes a new instance of the ServiceClient class.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Reliability",
"CA2000:Dispose objects before losing scope",
Justification = "The created objects should be disposed on caller's side")]
protected ServiceClient()
: this(CreateRootHandler())
{
}
/// <summary>
/// Initializes a new instance of the ServiceClient class.
/// </summary>
/// <param name="handlers">List of handlers from top to bottom (outer handler is the first in the list)</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Reliability",
"CA2000:Dispose objects before losing scope",
Justification = "The created objects should be disposed on caller's side")]
protected ServiceClient(params DelegatingHandler[] handlers)
: this(CreateRootHandler(), handlers)
{
}
/// <summary>
/// Initializes ServiceClient using base HttpClientHandler and list of handlers.
/// </summary>
/// <param name="rootHandler">Base HttpClientHandler.</param>
/// <param name="handlers">List of handlers from top to bottom (outer handler is the first in the list)</param>
protected ServiceClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers)
{
InitializeHttpClient(rootHandler, handlers);
}
/// <summary>
/// Create a new instance of the root handler.
/// </summary>
/// <returns>HttpClientHandler created.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Reliability",
"CA2000:Dispose objects before losing scope",
Justification = "The created objects should be disposed on caller's side")]
protected static HttpClientHandler CreateRootHandler()
{
// Create our root handler
#if NET45
return new WebRequestHandler();
#else
return new HttpClientHandler
{
ClientCertificateOptions = ClientCertificateOption.Automatic
};
#endif
}
/// <summary>
/// Gets the HttpClient used for making HTTP requests.
/// </summary>
public HttpClient HttpClient { get; protected set; }
/// <summary>
/// Gets the UserAgent collection which can be augmented with custom
/// user agent strings.
/// </summary>
public virtual HttpHeaderValueCollection<ProductInfoHeaderValue> UserAgent
{
get { return HttpClient.DefaultRequestHeaders.UserAgent; }
}
/// <summary>
/// Get the HTTP pipelines for the given service client.
/// </summary>
/// <returns>The client's HTTP pipeline.</returns>
public virtual IEnumerable<HttpMessageHandler> HttpMessageHandlers
{
get
{
var handler = FirstMessageHandler;
while (handler != null)
{
yield return handler;
DelegatingHandler delegating = handler as DelegatingHandler;
handler = delegating != null ? delegating.InnerHandler : null;
}
}
}
/// <summary>
/// Sets retry policy for the client.
/// </summary>
/// <param name="retryPolicy">Retry policy to set.</param>
public virtual void SetRetryPolicy(RetryPolicy retryPolicy)
{
if (retryPolicy == null)
{
throw new ArgumentNullException("retryPolicy");
}
RetryDelegatingHandler delegatingHandler =
HttpMessageHandlers.OfType<RetryDelegatingHandler>().FirstOrDefault();
if (delegatingHandler != null)
{
delegatingHandler.RetryPolicy = retryPolicy;
}
else
{
throw new InvalidOperationException(Properties.Resources.ExceptionRetryHandlerMissing);
}
}
/// <summary>
/// Dispose the ServiceClient.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose the HttpClient and Handlers.
/// </summary>
/// <param name="disposing">True to release both managed and unmanaged resources; false to releases only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
// Dispose the client
HttpClient.Dispose();
HttpClient = null;
FirstMessageHandler = null;
HttpClientHandler = null;
}
}
/// <summary>
/// Initializes HttpClient using HttpClientHandler.
/// </summary>
/// <param name="httpClientHandler">Base HttpClientHandler.</param>
/// <param name="handlers">List of handlers from top to bottom (outer handler is the first in the list)</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Reliability",
"CA2000:Dispose objects before losing scope",
Justification = "We let HttpClient instance dispose")]
protected void InitializeHttpClient(HttpClientHandler httpClientHandler, params DelegatingHandler[] handlers)
{
HttpClientHandler = httpClientHandler;
DelegatingHandler currentHandler = new RetryDelegatingHandler();
currentHandler.InnerHandler = HttpClientHandler;
if (handlers != null)
{
for (int i = handlers.Length - 1; i >= 0; --i)
{
DelegatingHandler handler = handlers[i];
// Non-delegating handlers are ignored since we always
// have RetryDelegatingHandler as the outer-most handler
while (handler.InnerHandler is DelegatingHandler)
{
handler = handler.InnerHandler as DelegatingHandler;
}
handler.InnerHandler = currentHandler;
currentHandler = handlers[i];
}
}
var newClient = new HttpClient(currentHandler, false);
FirstMessageHandler = currentHandler;
HttpClient = newClient;
Type type = this.GetType();
HttpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(type.FullName,
GetAssemblyVersion()));
}
/// <summary>
/// Get the assembly version of a service client.
/// </summary>
/// <returns>The assembly version of the client.</returns>
private string GetAssemblyVersion()
{
Type type = this.GetType();
string version =
type
.Assembly
.FullName
.Split(',')
.Select(c => c.Trim())
.First(c => c.StartsWith("Version=", StringComparison.OrdinalIgnoreCase))
.Substring("Version=".Length);
return version;
}
}
}