I have the following code:
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<MyConfig>(Configuration.GetSection("MySection"));
services.AddSingleton<IMyClass>(sp => new MyClass(sp.GetService<IOptions<MyConfig>>()));
}
This registers a singleton for MyClass and now I can have my controllers take a constructor argument of type IMyClass. This works as intended.
The MyClass is only instantiated first when a controller requires an IMyClass. However, I would like MyClass to be instantiated before anyone ever asks for it (since it does some work in it's constructor that takes a little while).
I could do something like:
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<MyConfig>(configuration.GetSection("MySection"));
var myinstance = new MyClass(/*...*/); // How do I get MyConfig in here?
services.AddSingleton<IMyClass>(myinstance);
}
...but then I can't get to the configuration since I don't have a reference to an IServiceProvider (The sp variable in the first code example). How do I get to the sericeprovider or what would I have to do to make sure the instance is initialized as soon as possible?
Initialize()" method instead of the constructor or something but either way the work needs to be/get done and I want it to be done ASAP (on startup) instead of on the first request.