Home > Software engineering >  How do I make a .NET Core 6 Top-Level statement template async?
How do I make a .NET Core 6 Top-Level statement template async?

Time:04-29

I'm follwoing this guide: https://docs.microsoft.com/en-us/dotnet/core/extensions/configuration and I don't understand how to make my application work as an async Main method.

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.

If I put the client inside the ConfigureAppConfiguration, is fails saying: The await operator can only be used within an async labmda expression. How do I make my console app to be async?

Now I want to instantiate MyClient, and use it to make query, however, since its need so to await the result, I fails. I don't understand how to make the app async. How should I solve this?

CodePudding user response:

So i found the problem, i copied the .net 6 code example into a net5.0 existing application. After i recreated everything targeting .net 6, things work as expected.

  • Related