Правильный способ использовать httpclient как синглтон - PullRequest
0 голосов
/ 23 января 2019

Я пытаюсь заставить клиента ac # общаться с Rest Api.Одноэлементный клиент с универсальными методами для отправки запросов на получение / публикацию на сервер.Только я не уверен, что это правильный способ, и хотел бы получить отзывы об этом:

internal class ApiClient : HttpClient
{
    private static readonly Lazy<ApiClient> lazyApiClient =
        new Lazy<ApiClient>(() => new ApiClient());
    private static readonly ApiClient instance = new ApiClient();
    static ApiClient() { }
    private ApiClient() : base()
    {

    }

    public static ApiClient Instance
    { get { return lazyApiClient.Value; } }

    private async Task<T> SendAsyncRequest<T>(HttpRequestMessage httpRequestMessage) where T : IApiResponse
    {
        using (httpRequestMessage)
        {
            HttpResponseMessage response = await SendAsync(httpRequestMessage, HttpCompletionOption.ResponseContentRead)
            .ConfigureAwait(false);
            {
                response.EnsureSuccessStatusCode();
                string responeString = response.Content.ReadAsStringAsync().Result;
                return await response.Content.ReadAsAsync<T>();
            }
        }
    }

    public async Task<T> Get<T>(string uriString) where T : IApiResponse
    {
        if (string.IsNullOrEmpty(uriString)) throw new Exception("missing request url");
        HttpRequestMessage httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri(uriString) };
        return await SendAsyncRequest<T>(httpRequestMessage);
    }

    public async Task<T> Post<T>(string jsonContent, string uriString) where T : IApiResponse
    {
        if (string.IsNullOrEmpty(jsonContent)) throw new ArgumentNullException("missing json content");
        if (string.IsNullOrEmpty(uriString)) throw new Exception("missing request url");
        StringContent stringContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
        HttpRequestMessage httpRequestMessage = new HttpRequestMessage { Content = stringContent, Method = HttpMethod.Post, RequestUri = new Uri(uriString) };
        return await SendAsyncRequest<T>(httpRequestMessage);
    }
}
...