In my ASP.NET 5 app, I want to load some data from Azure into a cache inside my Startup.Configure method. The Azure SDK exposes async methods exclusively. Typically, calling an
Dotnet Core 3.x offers better support for this.
First, you could create a class for your caching process. Have it implement IHostedService
like below. There are just two functions to implement:
private readonly IServiceProvider _serviceProvider;
public SetupCacheService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
// Perform your caching logic here.
// In the below example I omit the caching details for clarity and
// instead show how to get a service using the service provider scope.
using (var scope = _serviceProvider.CreateScope())
{
// Example of getting a service you registered in the startup
var sampleService = scope.ServiceProvider.GetRequiredService();
// Perform the caching or database or whatever async work you need to do.
var results = sampleService.DoStuff();
var cacheEntryOptions = new MemoryCacheEntryOptions(){ // cache options };
// finish caching setup..
}
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
Now, in Starup.cs
public virtual void ConfigureServices(IServiceCollection services)
{
// Normal service registration stuff.
// this is just an example. There are 1000x ways to do this.
services.AddTransient(IYourService, ConcreteService);
// Here you register the async work from above, which will
// then be executed before the app starts running
services.AddHostedService();
}
And that's it. Note that my solution to this relied heavily on Andrew Lock's article. I'm very grateful for him taking the time to write that up.
From the link I posted by Andrew Lock,
The services will be executed at startup in the same order they are added to the DI container, i.e. services added later in ConfigureServices will be executed later on startup.
Hopefully this helps anyone looking for Dotnet core 3.x+ approach.