This solution should help me explain my desire
This commit is contained in:
69
RepositoryLibrary/HostedRepository.cs
Normal file
69
RepositoryLibrary/HostedRepository.cs
Normal file
@@ -0,0 +1,69 @@
|
||||
using SharedLibrary.Models;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace RepositoryLibrary
|
||||
{
|
||||
public class HostedRepository : IRepository
|
||||
{
|
||||
private readonly string _backendUrl;
|
||||
public static ConcurrentBag<HttpClient> ApiClient = new ConcurrentBag<HttpClient>();
|
||||
public HostedRepository()
|
||||
{
|
||||
_backendUrl = "http://localhost:56143";
|
||||
}
|
||||
public async Task<object> Lookup()
|
||||
{
|
||||
return await GetAsync<string>();
|
||||
}
|
||||
|
||||
private async Task<T> GetAsync<T>([CallerMemberName] string request = "")
|
||||
{
|
||||
string uri = GetUriString(request);
|
||||
var client = GetHttpClient();
|
||||
using (var response = await client.GetAsync(uri))
|
||||
{
|
||||
ReturnHttpClient(client);
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var model = await response.Content.ReadAsAsync<T>();
|
||||
if (model != null)
|
||||
{
|
||||
return model;
|
||||
}
|
||||
}
|
||||
var err = await response.Content.ReadAsAsync<RepositoryError>();
|
||||
if (err != null)
|
||||
{
|
||||
throw new Exception(err.Information);
|
||||
}
|
||||
var str = await response.Content.ReadAsStringAsync();
|
||||
throw new Exception(str);
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
private HttpClient GetHttpClient()
|
||||
{
|
||||
if (!ApiClient.TryTake(out HttpClient client))
|
||||
{
|
||||
client = new HttpClient();
|
||||
}
|
||||
return client;
|
||||
}
|
||||
private void ReturnHttpClient(HttpClient client)
|
||||
{
|
||||
ApiClient.Add(client);
|
||||
}
|
||||
private string GetUriString(string request)
|
||||
{
|
||||
return $"{_backendUrl}/api/{request}";
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user