Skip to main content

Template.Initializing event

Raised after the application has started and before its template is saved.

public static event Func<Task>? Initializing;

Remarks​

Subscribe in Program.cs before await app.RunAsync(). The callbacks run once RunAsync has started the application, so its services and routes are available to them. They are awaited one at a time, in the order they subscribed.

Each preparation of a template runs the callbacks again, so make external work safe to repeat. Reusing an existing prepared template runs no callbacks. A callback may make network calls, for example to load data or apply database migrations. Await network work and dispose connections and streams before the callback returns: an open connection cannot be saved in the template. Timers may remain registered; their countdown starts at instance start. Do not retain request-scoped services. An exception stops the application from being prepared, so it does not start.

Everything the callbacks leave in memory is identical in every instance. Create what must differ between instances, such as a random identifier, in a callback subscribed to Starting.

Examples​

An ASP.NET application serves itself one request, so that the route, its serializers and its queries are ready in every instance. WarmupAsync is in the Isoplane.AspNetCore package.

var app = builder.Build();
app.MapGet("/todos", (TodoStore store) => store.All());

Template.Initializing += async () =>
{
await app.WarmupAsync("/todos");
};

await app.RunAsync();

See Also​