![](/img/trans.png)
[英]how to instantiate a singleton class in Startup.cs and then use in net core?
[英]How to add data from async method in singleton in Startup.cs in net.core 3.0?
我正在嘗試從 HttpClient 獲取異步數據並將此數據作為單例添加到 Startup.cs 的 ConfigureServices 中
public static class SolDataFill
{
static HttpClient Client;
static SolDataFill()
{
Client = new HttpClient();
}
public static async Task<SolData> GetData(AppSettings option)
{
var ulr = string.Format(option.MarsWheaterURL, option.DemoKey);
var httpResponse = await Client.GetAsync(ulr);
var stringResponse = await httpResponse.Content.ReadAsStringAsync();
var wheather = JsonConvert.DeserializeObject<SolData>(stringResponse);
return wheather;
}
}
啟動文件
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration);
var settings = Configuration.GetSection("NasaHttp") as AppSettings;
var sData = await SolDataFill.GetData(settings);
services.AddSingleton<SolData>(sData);
}
有一個錯誤:只能將 await 與 async 一起使用。 如何將數據從異步方法添加到單例?
也許您應該考慮重新設計SolDataFill
以最終成為 DataService,而不是將所有內容添加到 DI 容器中。
然后每個需要數據的人都可以查詢它。 (這就是為什么我在此處添加緩存以不總是執行請求的原因)
public class SolDataFill
{
private readonly HttpClient _client;
private readonly AppSettings _appSettings;
private readonly ILogger _logger;
private static SolData cache;
public SolDataFill(HttpClient client, AppSettings options, ILogger<SolDataFill> logger)
{
_client = client;
_appSettings = options;
_logger = logger;
}
public async Task<SolData> GetDataAsync()
{
if(cache == null)
{
var ulr = string.Format(_appSettings.MarsWheaterURL, _appSettings.DemoKey);
_logger.LogInformation(ulr);
var httpResponse = await _client.GetAsync(ulr);
if(httpResponse.IsSuccessStatusCode)
{
_logger.LogInformation("{0}", httpResponse.StatusCode);
var stringResponse = await httpResponse.Content.ReadAsStringAsync();
cache = JsonConvert.DeserializeObject<SolData>(stringResponse);
return cache;
}
else
{
_logger.LogInformation("{0}", httpResponse.StatusCode);
}
}
return cache;
}
}
就像在您的問題的評論中寫的一樣,通過GetAwaiter().GetResult()
同步運行異步方法非常簡單。 但是在我每次看到這段代碼時的選項中,我個人認為隱藏了可以重構的代碼異味。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.