ASP.NET Core Fluent Interface Extensions

Last week Khalid Abuhakmeh wrote a very interesting blog post called Middleware Builder for ASP.NET Core which I highly recommend you read. In it, he attempts to write some extension methods to help with writing the Configure method in your ASP.NET Core Startup class with a fluent interface. I’ve taken his blog post to heart and gone on a mission to ‘fluent all the things’ in ASP.NET Core.

IApplicationBuilder and ILoggerFactory

This is an example of what your current Configure method might look like in a typical ASP.NET Core Startup class:

And this is the same code using the shorter, and prettier fluent interface style:

In the above code, you can see that I’ve added UseIf  and UseIfElse  extension methods to the IApplicationBuilder  which lets us use the fluent interface. What you’ll also notice is that ILoggerFactory  also has AddIf  and AddIfElse  extension methods.


I didn’t just stop there, I added simililar AddIf  and AddIfElse  extension methods for IConfigurationBuilder :


As if that wasn’t enough I also did the same with IServiceCollection with the same AddIf  and AddIfElse  extension methods. In my experience, these would be used less often but I’ve added them for completeness.

Fluent me up!

You can get these extension methods and much more by installing the Boilerplate.AspNetCore NuGet package or create a project using the ASP.NET MVC Boilerplate project template. Finally, if you are so inclined, you can also take a look at the code for these extension methods below: