You can access the service injection system after the application starts up.
For example, first write an extension to your IHost like this: (Put this method any static class you like)
public static IHost PostStart(this IHost host)
{
using var scope = host.Services.CreateScope();
var services = scope.ServiceProvider;
// You can get your services here.
var configuration = services.GetService<IConfiguration>();
// And right here, you can initialize your properties. Do anything you like.
return host;
}
After writting your PostStart method, call it after your program starts.
Change your Program.cs file.
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args)
.Build()
.PostStart() // <- add this.
.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>());
}
}
As you mentioned, you want to initialize some properties for a service. So just add your data store as a singleton dependency.
// Startup.cs ConfigureServices method.
services.AddSingleton<YourDataStore>();
And in your PostStart method, access it with:
// PostStart method.
var data = services.GetRequiredService<YourDataStore>();
var apiService = services.GetRequiredService<YourAPIService>();
data.YourProperty = apiService.GetResultFromYourDataSource();