Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Examples of Repository Pattern with consuming an external REST web service via HttpClient?

Tags:

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?

like image 659
Jiveman Avatar asked Jul 14 '16 16:07

Jiveman


People also ask

What is repository pattern in Web API?

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.

What are repository patterns?

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.

Why we use repository pattern in Web API?

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.


1 Answers

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.

like image 97
Andrei Avatar answered Sep 27 '22 23:09

Andrei