如何在net.core 3.0的Startup.cs中添加来自singleton中异步方法的数据



我正试图从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;
}
}

启动.cs

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一起使用。如何将异步方法中的数据添加到singleton?

也许您应该考虑重新设计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()同步的异步方法非常简单。但在我的眼镜里,每次我看到这些代码时,我个人都认为隐藏着一种可以重构的代码气味。

最新更新