This solution should help me explain my desire

This commit is contained in:
Tracy Pearson
2020-10-19 12:55:29 -04:00
parent 4e9964435b
commit 92445d4e7a
18 changed files with 280 additions and 71 deletions

View 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}";
}
}
}

View File

@@ -0,0 +1,10 @@
using System;
using System.Threading.Tasks;
namespace RepositoryLibrary
{
public interface IRepository
{
Task<object> Lookup();
}
}

View File

@@ -0,0 +1,17 @@
using SharedLibrary.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RepositoryLibrary
{
public class LocalRepository : IRepository
{
public async Task<object> Lookup()
{
throw new RepositoryException();
}
}
}

View File

@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="5.2.7" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SharedLibrary\SharedLibrary.csproj" />
</ItemGroup>
</Project>