Skip to content

Instantly share code, notes, and snippets.

@GeradeDev
Created July 3, 2019 14:52
Show Gist options
  • Save GeradeDev/d469c623413316d0d8e2b9fc7ca3fc1b to your computer and use it in GitHub Desktop.
Save GeradeDev/d469c623413316d0d8e2b9fc7ca3fc1b to your computer and use it in GitHub Desktop.
public static void AddDefaultEndpoint<T>(this IServiceCollection services, string serviceName) where T : class
{
var clientName = typeof(T).ToString();
var options = ConfigureOptions(services);
ConfigureDefaultClient(services, clientName, serviceName, options);
ConfigureForwarder<T>(services, clientName);
}
private static RestEaseOptions ConfigureOptions(IServiceCollection services)
{
IConfiguration configuration;
using (var serviceProvider = services.BuildServiceProvider())
{
configuration = serviceProvider.GetService<IConfiguration>();
}
services.Configure<RestEaseOptions>(configuration.GetSection("restEase"));
return configuration.GetOptions<RestEaseOptions>("restEase");
}
public static void ConfigureDefaultClient(IServiceCollection services, string clientName, string serviceName, RestEaseOptions options)
{
services.AddHttpClient(clientName, client =>
{
var service = options.Services.SingleOrDefault(s => s.Name.Equals(serviceName, StringComparison.InvariantCultureIgnoreCase));
if (service == null)
{
throw new RestEaseServiceNotFoundException($"RestEase service: '{serviceName}' was not found.",
serviceName);
}
client.BaseAddress = new UriBuilder
{
Scheme = service.Scheme,
Host = service.Host,
Port = service.Port
}.Uri;
});
}
public static void ConfigureForwarder<T>(IServiceCollection services, string clientName) where T : class
{
services.AddTransient<T>(c => new RestClient(c.GetService<IHttpClientFactory>().CreateClient(clientName))
{
RequestQueryParamSerializer = new QueryParamSerializer()
}.For<T>());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment