liveBook · Manning

AddSingleton

As explained in ASP.NET Core in Action, 3e

AddSingleton is an ASP.NET Core service-registration method that registers a service with singleton lifetime.

AddSingleton is an ASP.NET Core dependency-injection registration method. It tells the built-in DI container to use one instance of a service throughout the application. section 9.1 section 9.2

Use AddSingleton in these forms:

  • Register a concrete type directly: builder.Services.AddSingleton<MessageFactory>(); The container creates and reuses the registered type. section 9.1
  • Register an existing object: builder.Services.AddSingleton(new EmailServerSettings("smtp.server.com", 25)); The supplied object is always treated as a singleton. section 9.2
  • Choose another lifetime when each request needs a newly created object; a factory lambda can be registered with AddScoped instead. section 9.2

Registering a shared service

WebApplicationBuilder builder = WebApplication.CreateBuilder(args); builder.Services.AddSingleton<MessageFactory>(); WebApplication app = builder.Build(); The container can now create MessageFactory when a dependency requires it and reuse the same instance throughout the application.

How ASP.NET Core in Action, 3e covers it

How deep it goes
Defines singleton lifetime and demonstrates type and object registration, but defers detailed lifetime discussion and asynchronous factories.
Examples
Uses MessageFactory and EmailServerSettings to demonstrate type registration and reuse of a supplied configuration object.
What you can do after
Operate/configure ASP.NET Core's DI container by registering a reusable service or preconstructed object with AddSingleton.
How it connects
Connects dependency injection, service lifetime, IServiceCollection, IServiceProvider, and the factory pattern.

Also explained in

Compare how 2 books explain AddSingleton →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.