Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 3 - immediately instantiate a singleton after services.AddSingelton<IMySingletone, MySingletone>();

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.

like image 296
Lopuch Avatar asked Oct 31 '25 03:10

Lopuch


1 Answers

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.

like image 148
Nkosi Avatar answered Nov 02 '25 18:11

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!