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;
    }

    // ...
}

Comments
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.

My Pluralsight Courses

K.Scott Allen OdeToCode by K. Scott Allen
What JavaScript Developers Should Know About ECMAScript 2015
The Podcast!