雖然這個類別會實作 IDisposable,但不建議在 using 陳述式內加以宣告及具現化,因為處置 HttpClient.cs 物件時,底層通訊端並不會立即釋放,而這可能會導致「通訊端耗盡」問題。
在Dependency Injection 中使用Singleton或是宣告靜態物件
開發人員遇到的另一個問題是在長時間執行的處理序中使用 HttpClient 的共用執行個體時。 在 HttpClient 具現化為 singleton 或靜態物件的情況下,其並無法處理 DNS 變更
例如:
1 2 3 4 5 6 7 8 9 10 11 12
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen();
builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen();
// 加上這一行 builder.Services.AddHttpClient();
具名HttpClient
應用程式需要不同的HttpClient用法或是設定。
1 2 3 4 5 6 7 8 9 10 11 12 13
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen();