I am using dependency injection on a project to inject services using Unity dependency injection
private async Task<T> GetResult<T>(HttpResponseMessage response)
{
if (typeof(T) == typeof(byte[]))
{
return await(response.Content.ReadAsByteArrayAsync() as Task<T>);
}
else if (typeof(T) == typeof(System.IO.Stream))
{
return await(response.Content.ReadAsStreamAsync() as Task<T>);
}
else if (typeof(T) == typeof(string))
{
return await(response.Content.ReadAsStringAsync() as Task<T>);
}
else
{
return jsonService.Deserialize<T>(await response.Content.ReadAsStringAsync());
}
}
I am injecting the json service in the constructor.
IJsonService jsonService;
public HttpClientService(IJsonService _jsonService)
{
jsonService = _jsonService;
}
The question that i have is as follows. Is the JSON deserialization a concern of HTTPService or should I remove the following from the http service? (if the de-serialization fails it returns null)
return jsonService.Deserialize<T>(await response.Content.ReadAsStringAsync());
The Json Service is as follows
public class JsonService : IJsonService
{
public T Deserialize<T>(string input)
{
return JsonConvert.DeserializeObject<T>(input);
}
public string Serialize<T>(T input)
{
return JsonConvert.SerializeObject(input);
}
}
JsonConvert.DeserializeObject<string>(await response.Content.ReadAsStringAsync())
etc do such that you couldn't just have the one branch and always need anIJsonService
?IJsonService.Deserialize<string>(someString)
allowed to be different tosomeString
? Yourtypeof
checks could be removed if there is no difference, and then you "always need" an IJsonService, even if you optimise its use away.