FarmMapsApiClient_WURtest/FarmmapsApi/Extensions.cs
2020-03-25 21:32:28 +01:00

53 lines
1.8 KiB
C#

using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using FarmmapsApi.HttpMessageHandlers;
using FarmmapsApi.Models;
using FarmmapsApi.Services;
using IdentityModel.Client;
using Microsoft.Extensions.DependencyInjection;
namespace FarmmapsApi
{
public static class Extensions
{
public static IServiceCollection AddFarmmapsServices(this IServiceCollection serviceCollection,
Configuration configuration)
{
return serviceCollection
.AddSingleton(configuration)
.AddSingleton<IDiscoveryCache>(sp =>
{
var httpFactory = sp.GetRequiredService<IHttpClientFactory>();
return new DiscoveryCache(configuration.DiscoveryEndpointUrl,
() => httpFactory.CreateClient());
})
.AddSingleton<HttpClientSettings>()
.AddSingleton<FarmmapsEventHub>()
.AddTransient<OpenIdConnectService>()
.AddTransient<FarmmapsAuthenticationHandler>()
.AddHttpClient<FarmmapsApiService>()
.AddHttpMessageHandler<FarmmapsAuthenticationHandler>()
.Services;
}
public static async Task PollTask(TimeSpan retryTime, Func<CancellationTokenSource, Task> callback)
{
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
do
{
try
{
await callback(tokenSource);
await Task.Delay(retryTime, token);
}
catch
{
// ignored
}
} while (!token.IsCancellationRequested);
}
}
}