在我的 .Net 核心應用程式中,我有 NamedHttpClient 和 TypedHttpClient。我需要使用 NamedClient 作為 TypedHttpClient 中的默認 httpclient。
我的配置服務:
public static IServiceCollection ConfigureServiceOptions(this IServiceCollection services, IConfiguration config)
{
IConfigurationSection serverSection = config.GetSection(nameof(ServerOptions));
services.Configure<ServerOptions>(serverSection);
//Named
services.AddHttpClient("defaultHttpClient", client =>
{
client.BaseAddress = new System.Uri(dataServerSection.Get<ServerOptions>().ServerUrl);
client.DefaultRequestHeaders.Add("Accept", "application/xml, */*");
client.DefaultRequestHeaders.Add("User-Agent", "Server v1.0.0");
});
}
//startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureServiceOptions(Configuration);
//Adding Typed
services.AddHttpClient<DataService>(); //I need to use defaultHttpClient as HttpClient Inside DataService
}
到目前為止,我找到了 3 種方法來做到這一點,不確定任何方法是否有任何陷阱
方式一:
services.AddHttpClient<DataService>();
public class DataService
{
private HttpClient Client { get;}
public DataService(/*need to pass this otherwise cant resolve*/ HttpClient client, IHttpClientFactory factory)
{
Client = factory.CreateClient("defaultHttpClient");
}
}
在方式 1 中,我需要在建構式中有額外的 HttpClient 客戶端引數。否則 DataService 不會被決議。
方式2:
services.AddTransient<DataService>( cfg =>
{
var clientFactory = cfg.GetRequiredService<System.Net.Http.IHttpClientFactory>();
var httpClient = clientFactory.CreateClient("defaultHttpClient");
return new DataService(httpClient);
});
public class DataService
{
private HttpClient Client { get;}
public DataService(HttpClient client)
{
Client = client;
}
}
方式3:
services.AddTransient<DataService>();
public class DataService
{
private HttpClient Client { get;}
public DataService(IHttpClientFactory factory)
{
Client = factory.CreateClient("defaultHttpClient");
}
}
我認為 Way2 和 Way3 可能相同。不確定是否有任何區別。
有人可以告訴推薦的方法是什么嗎?或者是否有其他方法?
uj5u.com熱心網友回復:
由于您實際上并沒有為“方式 1”設定型別化客戶端DataService沒有多大意義,它基本上是“方式 3”,但有額外的步驟。
“方式 2”使服務代碼更清晰,但如果以后需要新的依賴項,維護起來會變得很麻煩。
“方式 3”是HttpClient在檔案中顯示使用命名的方式,所以我會使用它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/414074.html
標籤:
