.NET Core Service Installers

How to configure .NET core DI services without polluting startup class

The Startup class

The Startup class is where:

  • The app’s request handling pipeline is defined, as a series of middleware components.

Dependency injection (services)

ASP.NET Core includes a built-in dependency injection (DI) framework that makes configured services available throughout an app.

public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<RazorPagesMovieContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MovieCtx"));
//register all the dependencies
//register ...
//register ...
//register ...
}

How can we cleanup our startup class and make our DI more manageable and maintainable?

Create an interface

public interface IInstaller
{
void InstallServices(IServiceCollection services, IConfiguration configuration);
}
public class ServicesInstaller : IInstaller
{
public void InstallServices(IServiceCollection services, IConfiguration configuration)
{

services.AddControllers().AddNewtonsoftJson();
services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.AllowAnyOrigin();
policy.AllowAnyMethod();
policy.AllowAnyHeader();
});
});
public static class InstallerExtensions
{
public static void InstallServicesInAssembly(this IServiceCollection services, IConfiguration configuration)
{

var installers = typeof(Startup).Assembly.ExportedTypes.Where(x =>
typeof(IInstaller).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract).Select(Activator.CreateInstance).Cast<IInstaller>().ToList();
installers.ForEach(installer => installer.InstallServices(services, configuration));
}
}
public void ConfigureServices(IServiceCollection services)
{
services.InstallServicesInAssembly(Configuration);
}

Full code

Full Code for this can be found on my github repo-