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

