亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 HttpClient 處理數據提供者實例?

如何使用 HttpClient 處理數據提供者實例?

C#
ITMISS 2023-12-17 10:20:03
我已經使用存儲庫模式創建了我的數據提供程序。首先,我設計了一個基礎存儲庫接口,如下所示:internal interface IGenericRepository<T, in TResourceIdentifier>{    Task<IEnumerable<T>> GetManyAsync();    Task<T> GetAsync(TResourceIdentifier id);    Task PutAsync(T model);    Task<T> PostAsync(T model);    Task DeleteAsync(TResourceIdentifier id);}然后我實現了它:public class GenericRepository<T, TResourceIdentifier> : IDisposable, IGenericRepository<T, TResourceIdentifier>     where T : class{    private bool _disposed;    protected HttpClientHelper<T, TResourceIdentifier> Client;    protected GenericRepository(string addressSuffix)    {        Client = new HttpClientHelper<T, TResourceIdentifier>(Properties.Settings.Url, addressSuffix);    }    public async Task<IEnumerable<T>> GetManyAsync()    {        return await Client.GetManyAsync();    }    // All other CRUD methods and dispose    public void Dispose()    {        Dispose(true);        GC.SuppressFinalize(this);    }    private void Dispose(bool disposing)    {        if(_disposed || !disposing) return;        if(Client != null)        {            var mc = Client;            Client = null;            mc.Dispose();        }        _disposed = true;    }}然后我為每個實體創建了自定義存儲庫接口。例如:internal interface IOrderRepository : IGenericRepository<Order, int>{    Task<IEnumerable<Order>> GetOrderBySomeConditionAsync(string condition );}最后,我實現了自定義存儲庫:public class OrderRepository : GenericRepository<Order, int>, IOrderRepository{    public OrderRepository(string addressSuffix) : base(addressSuffix)    {    }    public async Task<IEnumerable<Order>> GetOrderBySomeConditionAsync(string condition)    {        //get all the orders (GetManyAsync()) and then returns the ones meeting the condition    }}請注意,HttpClientHelper使用HttpClient,需要手動處置。我創建了一個 MVC Web 應用程序,并在類級別定義了存儲庫,如下所示:IOrderRepository _orderRepository = new OrderRepository();這會影響 Dispose,但卻是反模式。我在實現中缺少什么,即每次調用時都沒有釋放該實例?
查看完整描述

2 回答

?
慕萊塢森

TA貢獻1810條經驗 獲得超4個贊

您不應該在每次請求后都處理 HTTPClient。

因此,HttpClient旨在實例化一次并重用 在應用程序的整個生命周期中。實例化 HttpClient 每個請求的類都會耗盡可用套接字的數量 在重負載下。該問題將導致 SocketException 錯誤。 解決該問題的可能方法基于創建 HttpClient 對象作為單例或靜態,如此處所述 Microsoft 關于 HttpClient 使用的文章。


查看完整回答
反對 回復 2023-12-17
?
躍然一笑

TA貢獻1826條經驗 獲得超6個贊

在通用存儲庫中編寫 Dispose 方法并不意味著它會在您認為需要時自動調用。它旨在單獨調用,因此您必須使用using語句(就像您有所示),或代碼中的?Dispose?方法。

或者,您可以將該工作留給垃圾收集器。

如果您確信使用,您還應該在通用存儲庫中創建一個終結器GC.SuppressFinalize(this);

您還應該創建一個靜態類來保存 HttpClient。您必須使用 HttpResponseMessages 來滿足您的需求,或者 HttpContent。


查看完整回答
反對 回復 2023-12-17
  • 2 回答
  • 0 關注
  • 162 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號