04/08/2023
A typical discussion topic about Dependency Injection (DI) Containers is creating singleton classes. Although many discussions come to the conclusion that the singleton pattern can be converted directly to singleton with a DI container, that is not entirely true.
First concern is that many DI containers support creating a child or scoped containers. Singleton registrations are instantiated with different rules based on the contract of the container. In that case it is possible that a child container creates its own singleton instance - but this is generally not the case. Today most containers differentiate scoped registrations from singletons to handle this case.
Second concern is that most DI containers require the user to implement the singleton type with a public constructor. This ensures that the DI container can invoke the constructor. However, it also implies that any user code may just as well instantiate further objects from the type. Even worse, the declaration of the type does not reflect its intended use.
The third concern is that a user can create multiple DI containers in an application. Each container can have its own singletons, as nothing restricts not to register the same (singleton) type with multiple containers.
Find out more