Explain the working principle and purpose of the AddSingleton method in dependency injection context.
sobes.tech AI
Answer from AI
The AddSingleton method in the context of Dependency Injection in C# is used to register a service with a singleton lifetime. This means that the DI container will create a single instance of this service for the entire duration of the application and will return this same instance on every request.
The purpose of AddSingleton is to ensure that all components depending on this service use the same object, which is useful for services that need to maintain state or are resource-intensive to create.
Example usage:
services.AddSingleton<IMyService, MyService>();
Here, IMyService is the interface, and MyService is the implementation class. The service will be created on the first request and the same instance will be used thereafter.
This differs from AddTransient (which creates a new instance on each request) and AddScoped (which creates one instance per request/session).