liveBook · Manning

AddSingleton

As explained in Pro ASP.NET Core 7, Tenth Edition

AddSingleton is an ASP.NET Core dependency-injection registration method that reuses one service instance for the lifetime of the application.

AddSingleton registers a dependency-injection service whose implementation instance is created when first needed and reused for every later resolution. Register it through WebApplicationBuilder.Services with an interface and implementation type. section 14.3 section 14.4

Registering a response formatter

builder.Services.AddSingleton<IResponseFormatter, HtmlResponseFormatter>(); An endpoint can request the registered interface as a parameter. ASP.NET Core inspects the handler parameters, resolves IResponseFormatter, and supplies the shared HtmlResponseFormatter instance before invocation. section 14.3

Use AddSingleton when one service object should satisfy all dependencies:

  • Register an interface-to-implementation mapping with AddSingleton<T, U>(). section 14.4
  • Expect the implementation to be instantiated on first resolution and reused afterward. section 14.4
  • Choose AddScoped or AddTransient instead when dependencies need request-scoped or per-resolution lifetimes. section 14.4
  • Use IHttpContextAccessor as a singleton registration when another service, such as a session-backed cart, needs the current session. section 9.1.2
Listing 9.3 Creating the cart service in the Program.cs file in the SportsStore folder
using Microsoft.EntityFrameworkCore;
using SportsStore.Models;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

builder.Services.AddDbContext<StoreDbContext>(opts => {
    opts.UseSqlServer(
        builder.Configuration["ConnectionStrings:SportsStoreConnection"]);
});

builder.Services.AddScoped<IStoreRepository, EFStoreRepository>();

builder.Services.AddRazorPages();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession();
builder.Services.AddScoped<Cart>(sp => SessionCart.GetCart(sp));
builder.Services.AddSingleton<IHttpContextAccessor, 
    HttpContextAccessor>();
        
var app = builder.Build();

app.UseStaticFiles();
app.UseSession();

app.MapControllerRoute("catpage",
    "{category}/Page{productPage:int}",
    new { Controller = "Home", action = "Index" });
        
app.MapControllerRoute("page", "Page{productPage:int}",
    new { Controller = "Home", action = "Index", productPage = 1 });
        
app.MapControllerRoute("category", "{category}",
    new { Controller = "Home", action = "Index", productPage = 1 });
        
app.MapControllerRoute("pagination",
    "Products/Page{productPage}",
    new { Controller = "Home", action = "Index", productPage = 1 });
        
app.MapDefaultControllerRoute();
app.MapRazorPages();

SeedData.EnsurePopulated(app);

app.Run();

Shows AddSingleton alongside controllers, session, a scoped cart factory, and middleware configuration in a complete Program.cs setup. section 9.1.2

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Explains generic registration, handler resolution, first-use creation, and reuse, then contrasts scoped and transient lifecycles.
Examples
Uses IResponseFormatter with HtmlResponseFormatter and IHttpContextAccessor with HttpContextAccessor as registration examples.
What you can do after
Apply it via ASP.NET Core dependency injection to provide one reusable implementation instance wherever its service type is requested.
How it connects
Connects dependency injection with service lifecycles, scoped services, transient services, middleware, endpoints, and IHttpContextAccessor.

Also explained in

Compare how 2 books explain AddSingleton →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.