Extract to service
So far, for simplicity, we kept code in the controller. Before proceeding to call database, let’s move the business logic code to the service layer first.
Extract method without static
Extract class, make method public
Extract interface
Make controller use interface
In Program.cs, we want to register IBookService to resolve BookService.
This means when I need IBookService, give me BookService.
builder.Services.AddScoped<IBookService, BookService>();
Eventually, there will be more interfaces and services so we can pre-emptively extract this to a method.
public static class DependencyConfigurator
{
public static void RegisterDependencies(this WebApplicationBuilder builder)
{
builder.Services.AddScoped<IBookService, BookService>();
}
}
Back in Program.cs,
builder.RegisterDependencies();