How to immediately instantiate a singleton after
services.AddSingelton<IMySingleton, MySingleton>()
I'm using this dirty workaround for now (call GetService in every request):
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.ApplicationServices.GetService<IFirebaseApp_ForInjection>();
//......
}
I know my singleton should be instantiated when needed in constructor injection, but I don't need to inject it into any constructor.
If the target singleton has no explicitly injected dependencies, there is nothing stopping it from being instantiated before adding it to the services collection
public void ConfigureServices(IServiceCollection services) {
//...
IMySingleton instance = new MySingleton();
services.AddSingelton(instance)
//...
}
If there are dependencies, then another option would be similar to the currently shown workaround by injecting it into Configure method in startup
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IMySingleton instance) {
//...
}
That way any registered dependencies will be resolved and injected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With