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)
    // ...
    // ...

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();

           .AddRazorOptions(options =>

        return services;

    // ...

Gravatar Aftab Wednesday, August 31, 2016
Nice way of keeping it clean.Thank you and extension methods!!
Gravatar Muhammad Rehan Saeed Wednesday, August 31, 2016
I went with the same extension methods. I also wrote some extension methods that will help in this scenario and when you want to use if-statements to conditionally add services or middleware. Check it out: http://rehansaeed.com/asp-net-core-fluent-interface-extensions/
Gravatar Eric Hoff Wednesday, August 31, 2016
I've tried this in my projects, but then the extension classes got busy and messy. Adding more classes added more files. It felt like pushing papers from one side of the desk to the other.
Art Sunday, September 11, 2016
ViewWithControllerViewLocationExpander()? I wish I knew what the inside of this class looked like - anybody else?
Gravatar Manoj Kulkarni Wednesday, September 21, 2016
Nice. Thank you for these extension methods
Gravatar Sergey Thursday, September 22, 2016
Great tips. Thanks!
Comments are closed.