The Configure and ConfigureServices methods in ASP.NET Core tend to become bloated in larger projects. The problem is that larger projects can require lots of configuration, and the configuration requires lots of options. You open a project and there are dozens, even hundreds of lines of code, to configure OIDC, Swagger, authorization policies, data services, claims transformations, cookie options, CORS policies, domain services, and the list goes on and on.
I encourage team members to use extension methods so each line of code in the Configure methods is simple and the configuration details are hidden (yet easy to find by navigating with F12).
For example, instead of using lambdas and overwhelming the reader with lots of configuration details ...
public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.Conventions.Add(new FeatureControllerModelConvention()); }) .AddRazorOptions(options => { options.ViewLocationFormats.Clear(); options.ViewLocationFormats.Add(@"{3}\{0}.cshtml"); options.ViewLocationFormats.Add(@"Features\Shared\{0}.cshtml"); options.ViewLocationExpanders.Add(expander); }); // and more code and more code and more code }
... Provide a high-level overview of the app configuration, but keep the details encapsulated.
public void ConfigureServices(IServiceCollection services) { services.AddCustomMvc(); services.AddSecurity(); services.AddCustomMediator(); services.AddDataStores(Configuration.GetConnectionString(nameof(LeagueDb))); }
Hide the configuration details in extension methods which are easy to find.
public static IServiceCollection AddCustomMvc(this IServiceCollection services) { var expander = new FeatureViewLocationExpander(); services.AddMvc(options => { options.Conventions.Add(new FeatureControllerModelConvention()); }) .AddRazorOptions(options => { options.ViewLocationFormats.Clear(); options.ViewLocationFormats.Add(@"{3}\{0}.cshtml"); options.ViewLocationFormats.Add(@"Features\Shared\{0}.cshtml"); options.ViewLocationExpanders.Add(expander); }); return services; }
There’s also a good chance you can re-use some of the extension methods, particularly in a micro-services environment. However, the primary focus is to make the startup code usable and readable, not re-usable.