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?
Repository Pattern is an abstraction of the Data Access Layer. It hides the details of how exactly the data is saved or retrieved from the underlying data source. The details of how the data is stored and retrieved is in the respective repository.
The Repository pattern. Repositories are classes or components that encapsulate the logic required to access data sources. They centralize common data access functionality, providing better maintainability and decoupling the infrastructure or technology used to access databases from the domain model layer.
What is a Repository pattern and why should we use it? With the Repository pattern, we create an abstraction layer between the data access and the business logic layer of an application. By using it, we are promoting a more loosely coupled approach to access our data from the database.
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 Task<string> GetStringAsync(string url) { using (var httpClient = new HttpClient()) { return 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With