How did I do?*

Abstract business logic dependencies with extension methods

Introduction

If your Startup class is beginning to look like nothing more than a long list of service injections, or you wish to keep the registrations relating to your business logic away from your main application code, then it's a good time to collate them into a single service extension method.

Take this example snippet from the ConfigureServices method in your Startup class:

builder.Services.AddScoped<IMyWebServiceClient, MyWebServiceClient>();
builder.Services.AddScoped<IMyBusinessLogicService, MyBusinessLogicService>();
builder.Services.AddSingleton<IMyValidator, MyValidator>();
builder.Services.AddSingleton<IMyRepository, MyRepository>();

If your main application is an API or a web app, you're likely importing all of these interfaces and classes from other projects into a part of the code which shouldn't need to reference them directly. You may have noticed that many established packages from NuGet etc. allow you to import all of the available classes and methods using a simple service registration, such as:

builder.Services.AddExternalPackageCode();

This is a much tidier and simpler way to inject everything that is needed, and can be achieved by creating a service extension method.

Create an extension method

Create a new folder in your business logic project called "Extensions", and add a class called "MyApplicationServiceExtensions":

public static class MyApplicationServiceExtensions
{
    public static IServiceCollection AddMyApplication(this IServiceCollection services)
    {
        services.AddSingleton<IMovieRepository, MovieRepository>();
        services.AddScoped<IMyWebServiceClient, MyWebServiceClient>();
        services.AddScoped<IMyBusinessLogicService, MyBusinessLogicService>();
        services.AddSingleton<IMyValidator, MyValidator>();
        services.AddSingleton<IMyRepository, MyRepository>();

        return services;
    } 
}

Copy all of the service injections from Startup, but exclude the Builder object because there is no web host builder in this context. Then you can simply reference the Extensions namespace in your Startup class with:

builder.Services.AddMyApplication();

and remove the individual service registration, along with their associated using references.