【发布时间】:2016-12-13 14:02:00
【问题描述】:
举一个真实的例子。这是下面的类:
public class HttpClientWrapper : IHttpClientWrapper
{
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
private readonly IStatsDPublisher _statsDPublisher;
private readonly HttpClient _client;
public HttpClientWrapper(IStatsDPublisher statsDPublisher, string baseAddress)
{
_statsDPublisher = statsDPublisher;
_client = new HttpClient();
_client.BaseAddress = new Uri(baseAddress);
ServicePointManager.FindServicePoint(_client.BaseAddress).ConnectionLeaseTimeout = (int)TimeSpan.FromSeconds(60).TotalMilliseconds;
}
public async Task PostAsync<T>(string resource, T content)
{
var stringContent = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8,"application/json");
var name = typeof(T);
using (var timer = _statsDPublisher.StartTimer($"HttpClient.{name.Name}.Post"))
{
try
{
await _client.PostAsync(resource, stringContent).ContinueWith(
(postTask) =>
{
postTask.Result.EnsureSuccessStatusCode();
});
timer.StatName = $"{timer.StatName}.Success";
}
catch (Exception ex)
{
timer.StatName = $"{timer.StatName}.Failure";
Logger.ExtendedException(ex, "Failed to Post.", new {Url = resource, Content = content});
throw;
}
}
}
public async Task PutAsync<T>(string resource, T content)
{
var stringContent = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8,
"application/json");
var name = typeof(T);
using (var timer = _statsDPublisher.StartTimer($"HttpClient.{name.Name}.Put"))
{
try
{
await _client.PutAsync(resource, stringContent).ContinueWith(
(postTask) =>
{
postTask.Result.EnsureSuccessStatusCode();
});
timer.StatName = $"{timer.StatName}.Success";
}
catch (Exception ex)
{
timer.StatName = $"{timer.StatName}.Failure";
Logger.ExtendedException(ex, "Failed to Put.", new { Url = resource, Content = content });
throw;
}
}
}
} }
在 IoC 中,我们执行以下操作:
Bind<IHttpClientWrapper>()
.To<HttpClientWrapper>()
.InSingletonScope()
所以现在是一个单例。我应该假设每次我们调用 HttpClientWrapper 时,我们是在处理同一个 HttpClient 实例,还是每次我们创建一个新实例?我相信每次访问 HttpClientWrapper 时,尽管是单例,您都会创建一个新的 HttpClient 实例。可以请教吗?
谢谢
【问题讨论】:
标签: .net memory memory-management singleton