c# - 如何使 .NET Core 6 顶级语句模板异步?

标签 c# asp.net asp.net-core .net-core

我正在关注本指南:https://learn.microsoft.com/en-us/dotnet/core/extensions/configuration我不明白如何使我的应用程序作为异步 Main 方法工作。

using IHost host = Host.CreateDefaultBuilder(args)
     .ConfigureAppConfiguration((hostingContext, configuration) =>
     {
         configuration.Sources.Clear();
         ILogger logger = NullLogger.Instance;

         IHostEnvironment env = hostingContext.HostingEnvironment;

         configuration
             .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
             .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true, true);

         IConfigurationRoot configurationRoot = configuration.Build();
         ApiConfig options = new();
         configurationRoot.GetSection(nameof(ApiConfig)).Bind(options);
         
         var serviceCollection = new ServiceCollection();
         serviceCollection.AddHttpClient();
         serviceCollection.AddMemoryCache();
serviceCollection.AddSingleton<IMyClient, MyClient>();
         IServiceProvider provider = serviceCollection.BuildServiceProvider();

         IHttpClientFactory clientFactory = provider.GetRequiredService<IHttpClientFactory>();

     })
    .Build();

// Application code should start here.
     Result result = await myClient. Get(ApiConfig);
// If i put it here, the client is not available since its inside the //ConfigureAppConfiguration.

如果我将客户端放入ConfigureAppConfiguration 中,则会失败并提示:await 运算符只能在异步labmda 表达式中使用。 如何使我的控制台应用程序异步?

现在我想实例化 MyClient,并用它来进行查询,但是,由于它需要等待结果,所以我失败了。我不明白如何使应用程序异步。我该如何解决这个问题?

最佳答案

所以我发现了问题,我将.net 6代码示例复制到net5.0现有应用程序中。在我重新创建针对 .net 6 的所有内容后,一切都按预期进行。

关于c# - 如何使 .NET Core 6 顶级语句模板异步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72010883/

相关文章:

c# - 如何为 DataView 设置 RowFilter 不区分大小写

ASP.NET 应用程序未记录到 Windows 事件日志

基于先前记录的 Asp.Net 中继器格式项

c# - 如何在请求结束时释放资源并在 ASP.NET 5/Core 中处理注入(inject)的服务?

asp.net-core - ASP.NET Core 集成测试中的 WebApplicationFactory 和 TestServer

azure - 生成不记名 token 时签名无效

c# - 如何在不使用任何 OpenSource Dll 的情况下使用 C# 4.0 从文件夹中解压所有 .Zip 文件?

c# - 如何在中继器内获取标签而不是在 itemdatabound 中

asp.net - 在客户端 ASP .Net C# 上运行非托管 C++ 函数

c# - 将新设备添加到 xaml 布局设计器 Visual Studio 2015 UWP