ConfigureServices is the Startup method that registers application and custom services in the dependency-injection container. The host calls it before Configure, so registered services are available while the middleware pipeline is configured. section 30.3
A typical ConfigureServices workflow is:
- Receive the IServiceCollection that stores registrations. section 30.3
- Read configuration through IConfiguration injected into Startup. section 30.3
- Register framework services such as a database context, Identity, application services, and Razor Pages with Add* methods. section 30.3
- Let the host discover ConfigureServices by its conventional method name; Startup does not need to implement an interface. section 30.7
Listing 30.3 Registering services with DI in ConfigureServices
public class Startup
{
public IConfiguration Configuration { get; } #1
public Startup(IConfiguration configuration) #1
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services) #2
{
var conn = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<AppDbContext>(options => #3
options.UseSqlite(conn)); #3
services.AddDefaultIdentity<ApplicationUser>(options => #3
options.SignIn.RequireConfirmedAccount = true) #3
.AddEntityFrameworkStores<AppDbContext>(); #3
services.AddScoped<RecipeService>(); #4
services.AddRazorPages(); #5
services.AddScoped<IAuthorizationHandler, IsRecipeOwnerHandler>();
services.AddAuthorizationBuilder()
.AddPolicy("CanManageRecipe",
p => p.AddRequirements(new IsRecipeOwnerRequirement()));
}
public void Configure(IApplicationBuilder app) => { /* Not shown */ }
}
This example connects a configuration value to EF Core, Identity, a scoped application service, and Razor Pages registrations. section 30.3
