I've searched around quite a bit, but haven't found any good examples of consuming an external REST web service using a Repository Pattern in something like an ASP.NET MVC app, with loose coupling and meaningful separation of concerns. Almost all examples of repository pattern I find online are writing SQL data or using an ORM. I'd just like to see some examples of retrieving data using HttpClient but wrapped in a repository.
Could someone write up a simple example?
A simple example:
// You need interface to keep your repository usage abstracted
// from concrete implementation as this is the whole point of
// repository pattern.
public interface IUserRepository
{
Task<User> GetUserAsync(int userId);
}
public class UserRepository : IUserRepository
{
private static string baseUrl = "https://example.com/api/"
public async Task<User> GetUserAsync(int userId)
{
var userJson = await GetStringAsync(baseUrl + "users/" + userId);
// Here I use Newtonsoft.Json to deserialize JSON string to User object
var user = JsonConvert.DeserializeObject<User>(userJson);
return user;
}
private static async Task<string> GetStringAsync(string url)
{
using (var httpClient = new HttpClient())
{
return await httpClient.GetStringAsync(url);
}
}
}
Here is where/how to get Newtonsoft.Json
package.
Another option would be to reuse HttpClient
object and make your repository IDisposable
because you need to dispose HttpClient
when you done working with it. In my first example it happens right after HttpClient
usage at the end of using
statement.