Skip to content

Instantly share code, notes, and snippets.

@hamid-shaikh
Created July 14, 2019 08:35
Show Gist options
  • Save hamid-shaikh/7a766529e79cea8e108d53c657ca1594 to your computer and use it in GitHub Desktop.
Save hamid-shaikh/7a766529e79cea8e108d53c657ca1594 to your computer and use it in GitHub Desktop.
Refit + Prism Forms + Fusillade + ModernHttpClient
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Fusillade;
using ModernHttpClient;
using Newtonsoft.Json;
using Refit;
/// <summary>
/// Private and Public Variables
/// </summary>
/// <typeparam name="TInterfaceService"></typeparam>
public partial class ApiService<TInterfaceService>
{
readonly JsonSerializerSettings jsonSerializerSettings;
readonly Lazy<TInterfaceService> _background;
readonly Lazy<TInterfaceService> _userInitiated;
readonly Lazy<TInterfaceService> _speculative;
}
/// <summary>
/// Constructor Creation
/// </summary>
/// <typeparam name="TInterfaceService"></typeparam>
public partial class ApiService<TInterfaceService>
{
public ApiService()
{
jsonSerializerSettings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore,
DateTimeZoneHandling = DateTimeZoneHandling.Utc
};
_background = new Lazy<TInterfaceService>(() => CreateHttpClient(
new RateLimitedHttpMessageHandler(new NativeMessageHandler(), Priority.Background)));
_userInitiated = new Lazy<TInterfaceService>(() => CreateHttpClient(
new RateLimitedHttpMessageHandler(new NativeMessageHandler(), Priority.UserInitiated)));
_speculative = new Lazy<TInterfaceService>(() => CreateHttpClient(
new RateLimitedHttpMessageHandler(new NativeMessageHandler(), Priority.Speculative)));
}
}
/// <summary>
/// Private Methods
/// </summary>
/// <typeparam name="TInterfaceService"></typeparam>
public partial class ApiService<TInterfaceService>
{
TInterfaceService CreateHttpClient(HttpMessageHandler messageHandler)
{
var client = new HttpClient(messageHandler)
{
BaseAddress = new Uri(AppConstants.BaseAddress),
Timeout = TimeSpan.FromSeconds(AppConstants.Timeout)
};
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
//client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
return RestService.For<TInterfaceService>(client, new RefitSettings
{
ContentSerializer = new JsonContentSerializer(jsonSerializerSettings)
});
}
}
/// <summary>
/// IApiService<TInterfaceService> Implementation
/// </summary>
/// <typeparam name="TInterfaceService"></typeparam>
public partial class ApiService<TInterfaceService> : IApiService<TInterfaceService>
{
public TInterfaceService Speculative { get => _speculative.Value; }
public TInterfaceService UserInitiated { get => _userInitiated.Value; }
public TInterfaceService Background { get => _background.Value; }
}