A helper to fetch API services using Refit and Fusillade
Canfiguration can be done via appsetting.json file on inside code. You can configure host, timeout and serialize mode that represent ApiConfiguration object.
Object of ApiConfiguration
"GitHubService": {
"host": "https://api.github.com",
"timeout": 360,
"serializeMode": "SnakeCase"
}You need to define base interface for each module that api services provided, this will enable dependency injection registration on runtime and no need register each Refit interface. To provide it, you can create empty interface, then interit it to each Refit interface services.
Interface module:
public interface IGitHub {}Refit interface that inherit interface module:
[Headers("User-Agent: FetchData-Example")]
public interface IGitHubApi : IGitHub
{
[Get("/users/{username}")]
Task<GitHubProfile> GetUser(string username);
}First, you need ApiConfiguration instance before register services,
- From
appsettings.json
var githubConf = builder.GetSection("GitHubService").Get<ApiConfiguration>();
- From new instance
var githubConf = new ApiConfiguration { Host = "https://api.github.com", Timeout = 360, SerializeMode = SerializeNamingProperty.SnakeCase }
Then, create ApiServiceConfiguration instance with previous configuration
var githubServiceConf = new ApiServiceConfiguration
{
Configuration = githubConf,
Modules = new[] { typeof(IGitHub) }
};Register to dependency injection container in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// configure api services here
services.AddApiServices(githubServiceConf);
}The default implementation of DelegatingHandler provided this library, will only log http request and response in debug level. To enable it, provide ILoggerFactory to this library.
LoggerFactory
.Create(builder => builder.AddConsole().SetMinimumLevel(LogLevel.Debug))
.SetFetchDataLoggerFactory();You can provide your own DelegatingHandler implementation to customize authentication header & other stuff, and let FetchData use it. Add your DelegatingHandler before register services to dependency injection.
githubServiceConf.DelegatingHandler = typeof(YourOwnDelegatingHandler);FetchData also use Fusillade to drive HttpClient, you can read more about it in here
var githubService = serviceProvider.GetService<IApiService<IGitHubApi>>();var result = await githubService.Initiated.GetUser(username).ConfigureAwait(false);var result = await githubService.Background.GetUser(username).ConfigureAwait(false);var result = await githubService.Speculative.GetUser(username).ConfigureAwait(false);