Zubair Khakwani
Zubair Khakwani

Reputation: 438

DI Singleton Service Instantiates Twice

I register a service as Singleton in the program.cs file like this.

builder.Services.AddSingleton<ITest, Test>();

and if I request an instance of it in program.cs

var testService = builder.Services.BuildServiceProvider()
                                  .GetRequiredService<ITest>();

It creates a new object which is the first object, but when I request it through constructor injection in some other service it creates a new object again. Shouldn't it return the first object that it created while startup in Program.cs?

Note : This behavior is only if I request service in the program.cs other than that it returns the same object, even if I request it using IServiceProvider.GetRequiredService();

i have tested the same scenario in dot net 5 web api as well in which i register the service in ConfigureServices method of Startu.cs file

services.AddSingleton<ITest, Test>();

and request the service in Configure method like this

 var test = app.ApplicationServices.GetRequiredService<ITest>();

and when i request it in constructor in some other service it will return the same object.

Why?

Upvotes: 6

Views: 2156

Answers (1)

nvoigt
nvoigt

Reputation: 77364

In your starup file, you don't have a service provider yet. You only have the Services property that allows you to define your services.

Since you want to instantiate one, you call builder.Services.BuildServiceProvider() which builds a service provider for you, that you then use to get a service. Inside that service provider, your service lives as singleton.

Then, you proceed in your application and the framework, being happy that you defined your services, then builds it's own service provider. Which you can access via app.ApplicationServices. That one, too, has a single instance of your class, since it's a singleton.

And from now on, since all your services and controllers use the service provider created by the framework, not the one you created manually in startup, all of them will get the same instance.

Upvotes: 9

Related Questions