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

后端 未结 1 801
忘掉有多难
忘掉有多难 2021-02-05 10:13

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

1条回答
  •  佛祖请我去吃肉
    2021-02-05 10:22

    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 GetUserAsync(int userId);
    }
    
    public class UserRepository : IUserRepository
    {
        private static string baseUrl = "https://example.com/api/"
    
        public async Task 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(userJson);
            return user;
        }
    
        private static async Task 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.

    0 讨论(0)
提交回复
热议问题