For instance, multiple requests are coming and each requests this singleton service from DI. With the service added using
public static IServiceCollection AddSingleton<TService>(
this IServiceCollection services,
Func<IServiceProvider, TService> implementationFactory)
where TService : class
overload, would the factory method be guaranteed to run only once?
CodePudding user response:
The documentation isn't very specific, but you can assure that, within the context of the built-in container (MS.DI), the factory is guaranteed to be called at most once per IServiceProvider instance.
Although I haven't got strong evidence to prove this claim, complete applications and frameworks are built around the assumption that this is guaranteed.
Please note the following:
- Although any 3rd-party adapter implementation might have less strong guarantees, one should expect the same behavior as the MS.DI.
- The definition of a Singleton is that it is "scoped" to the lifetime of a single container instance, i.e. the
IServiceProvider
. MS.DI follows this definition, which means that creating a newIServiceProvider
based on the sameIServiceCollection
(e.g. by callingBuildServiceProvider()
) will allow the factory delegate to be called again by that newIServiceProvider
.
In an ASP.NET Core application (unless you override this), the framework manages the creation of the ServiceCollection
and its resulting ServiceProvider
. This means that there is only one ServiceProvider
for the duration of the application, which means your Singleton factory delegate is called just once.
When you start calling CreateServiceProvider()
manually, however, you will be creating extra IServiceProvider
instances, and with it its own Singleton instances, which means extra calls to your Singleton factory delegates.