I used to get a JSON file with some configuration settings from the file system, using this class:
public class ConfigurationFileService : IConfigurationService
{
private readonly IConfigurationManager _configurationManager;
public ConfigurationFileService(IConfigurationManager configurationManager)
{
_configurationManager = configurationManager;
}
public Configuration GetConfiguration(int agentId)
{
var path = _configurationManager.GetAppSetting("pathToConfigurationFile");
var Configuration = JObject.Parse(File.ReadAllText(string.Format(path, agentId)));
return Configuration.ToObject<Configuration>();
}
}
Now I will be getting that from an API (it will return exactly the same JSON), so I need to change the implementation of the IConfigurationService
, I have done this so far.
public class ConfigurationApiClient : IConfigurationService
{
private readonly HttpClient _client;
public ConfigurationApiClient()
{
_client = new HttpClient();
_client.BaseAddress = new Uri(""); //TODO Add base url
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public Configuration GetConfiguration(int agentId)
{
return GetConfigurationAsync(agentId).Result;
}
private async Task<Configuration> GetConfigurationAsync(int agentId)
{
try
{
var response = await _client.GetAsync(""); // TODO add the url
response.EnsureSuccessStatusCode();
var Configuration = await response.Content.ReadAsAsync<Configuration>();
return Configuration;
}
catch(HttpRequestException ex)
{
throw new ConfigurationException(string.Format("Exception when getting settings for agent: {0}", agentId), ex);
}
}
The interface is very simple:
public interface IConfigurationService
{
Configuration GetConfiguration(int agentId);
}
I am not sure about a couple of things:
The way I reuse the
httpclient
. I have seen that the recommendation is not to dispose it after each request, so I guess putting it in the constructor is a good option as the class itself will be injected.The usage of one public method with the signature of the interface, that blocks the result of the asynchronous method (given that's the correct way of getting the result asynchronously).
GetConfiguration
toTask<Configuration>
? \$\endgroup\$ – mjolka Nov 12 '15 at 13:39IConfigurationService
to look like this:public interface IConfigurationService { Task<Configuration> GetConfigurationAsync(int agentId); }
\$\endgroup\$ – mjolka Nov 12 '15 at 13:51