举一个真实的例子。以下是以下课程:
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,尽管是Singleton,您都会创建一个新的HttpClient实例。你能告诉我吗?
由于
答案 0 :(得分:1)
Singleton意味着您在整个应用程序中只有一个类的单个实例。您根本无法创建该类的另一个实例。使用单例内的对象将始终返回相同的实例。 但是,您仍然可以在单例之外创建其他类的新实例。 所以答案显然是“不”。
希望有所帮助。