Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make the ConfigureServices method async in Startup.cs

I need to add a couple of await functions in ConfigureServices in Startup.cs and am running into an issue.

System.InvalidOperationException Unable to find the required services. Please add all the required services by calling 'IServiceCollection.AddMvc()' inside the call to 'IApplicationBuilder.ConfigureServices(...)' or 'IApplicationBuilder.UseMvc(...)' in the application startup code.

As seen by the code below, AddMvc & UseMvc are in their correct locations, however, I still get this error.

public async void ConfigureServices(IServiceCollection services) {     ...     await manager.Initialize();     var data = await manager.GetData();     ...     services.AddMvc(); }  public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory) {     ...     app.UseMvc();     .... } 

Is it possible to make ConfigureServices an async function?

like image 487
Brian Vu Avatar asked Jun 01 '16 15:06

Brian Vu


People also ask

Can startup configure be async?

You can do some asynchronous work, but the method is synchronous and you cannot change that. This means you need synchronously wait for async calls to be completed. You don't want to return from a Startup method if the startup is not finished yet, right?

What does configure () and ConfigureServices () methods do startup CS do?

cs file in a standard ASP.NET Core application. The startup class contains two methods: ConfigureServices(): Registers the services that your application will need. Configure(): Configures the middleware pipeline that controls how the application processes the HTTP requests and sends the response.

What is difference between configure and ConfigureServices?

They are the ConfigureServices method and the Configure method. In the Startup class, we actually do two things: Configure Service(): It is used to add services to the container and configure those services. basically, service is a component that is intended for common consumption in the application.

Is configure or ConfigureServices called first?

At run time, the ConfigureServices method is called before the Configure method. This is so that you can register your custom service with the IoC container which you may use in the Configure method.


1 Answers

No, you can't. Doing that would result in a race condition.

Instead, consider making your operation synchronous or using .Wait()/.Result (depending on whether the async method returns data or not) to block until the asynchronous task completes.

like image 123
Kévin Chalet Avatar answered Oct 04 '22 06:10

Kévin Chalet