DI with ASP.NET Core
The most common project type that uses DI extensively is an ASP.NET Core project. In this section, we will look at some of the special cases of DI when building web apps and services.
Registering services for features using extension methods
With a complex ASP.NET Core project, you are likely to need to register many related services for each feature of the website or web service in Program.cs
, as shown in the following code:
builder.Services.AddScoped<IShoppingCart, InMemoryShoppingCart>();
builder.Services.AddScoped<ICustomerAccount, CustomerAccount>();
builder.Services.AddScoped<IUserRegistration, UserRegistration>();
It is good practice to define an extension method to group all these registrations, as shown in the following code:
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddNorthwindFeatures(
this IServiceCollection services)
{
services.AddScoped<IShoppingCart,...