OdeToCode IC Logo

Keeping a Clean Startup.cs in Asp.Net Core

Tuesday, August 30, 2016

In some applications the Configure and ConfigureServices methods of Startup.cs can become unwieldy. It’s not complicated logic, but with all the middleware and services and options to configure, the methods become long and messy.

I prefer to keep a series of simple, one-line method calls inside of both methods.

public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddCustomizedMvc();
    services.AddCustomizedIdentity();
    services.AddDataStores();
    // ...
}

All of the details for these method calls live inside extensions methods for IApplicationBuilder or IServiceCollection. Here’s an example. 

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddCustomizedMvc(this IServiceCollection services)
    {
        var locationFormat = @"Features\Shared\{0}.cshtml";
        var expander = new ViewWithControllerViewLocationExpander();

        services.AddMvc()
           .AddRazorOptions(options =>
           {
               options.ViewLocationFormats.Clear();
               options.ViewLocationFormats.Add(locationFormat);
               options.ViewLocationExpanders.Add(expander);
           });

        return services;
    }

    // ...
}