1 using Microsoft.AspNetCore.Builder;
2 using Microsoft.AspNetCore.Hosting;
3 using Microsoft.Extensions.DependencyInjection;
7 using System.Threading.Tasks;
24 public static void UseAsyncInitialization<TDependency>(
this IApplicationBuilder applicationBuilder, Func<TDependency, CancellationToken, Task> asyncInitializer)
26 if (applicationBuilder == null)
27 throw new ArgumentNullException(nameof(applicationBuilder));
28 if (asyncInitializer == null)
29 throw new ArgumentNullException(nameof(asyncInitializer));
31 applicationBuilder.UseAsyncInitialization((cancellationToken) => asyncInitializer(applicationBuilder.ApplicationServices.GetRequiredService<TDependency>(), cancellationToken));
40 public static void UseAsyncInitialization(
this IApplicationBuilder applicationBuilder, Func<CancellationToken, Task> asyncInitializer)
42 if (applicationBuilder == null)
43 throw new ArgumentNullException(nameof(applicationBuilder));
44 if (asyncInitializer == null)
45 throw new ArgumentNullException(nameof(asyncInitializer));
47 var applicationLifetime = applicationBuilder.ApplicationServices.GetRequiredService<IApplicationLifetime>();
48 Task initializationTask = null;
49 var tcs =
new TaskCompletionSource<object>();
51 async Task AsyncProcess()
53 using (applicationBuilder.ApplicationServices.CreateScope())
54 await asyncInitializer(applicationLifetime.ApplicationStopping).ConfigureAwait(
false);
57 applicationLifetime.ApplicationStarted.Register(() =>
59 initializationTask = AsyncProcess();
63 var applicationStopping = applicationLifetime.ApplicationStopping;
64 applicationBuilder.Use(async (context, next) =>
66 await tcs.Task.ConfigureAwait(
false);
67 if(!initializationTask.IsCompleted || applicationStopping.IsCancellationRequested)
69 context.Response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
72 await initializationTask.ConfigureAwait(
false);
73 await next().ConfigureAwait(
false);
static void UseAsyncInitialization(this IApplicationBuilder applicationBuilder, Func< CancellationToken, Task > asyncInitializer)
Runs a Task once applicationBuilder has started
Asynchronous initialization extensions for IApplicationBuilder