How to use Minimal APIs in .NET 8 without cluttering Program.cs
- Jul 5, 2024
Minimal APIs were first introduced in ASP.NET Core 6.0 and have been around for some time now. At a high level, Minimal APIs are a simplified way of building HTTP APIs with ASP.NET Core.
But why use Minimal APIs over the classic MVC / Controller workflow that we’re all familiar with?
- ASP.NET MVC is useful if you want to organise your code based on layers. Minimal APIs are useful if you would rather organise your code by features/slice, keeping related things together… but you can still keep a layered architecture with Minimal APIs if you prefer.
- MVC is opt-out, running an entire filter pipeline for each request, even if you don’t actually need all of it. When using Minimal APIs, you need to explicitly opt-in to validation, model binding, and any filters that you’d like to run on each request. Minimal API filters are also simpler, with the capability to do everything that MVC can.
- ASP.NET MVC’s convention based model can be difficult to understand and debug - it isn’t always clear exactly which routes would be discovered and configured via reflection, and getting this right can be error-prone especially early in the project. With Minimal API, routes are explicitly mapped, making Minimal API routes easier to understand and debug.
- Controllers can be harder to test, and tend to grow in complexity over time - I’ve seen controllers become a massive file with a equally massive constructor (upwards of 20 parameters); you’ll need to inject all those parameters when instantiating the class in a unit test, even if method you’re testing only uses one of those parameters…. leading to controllers sometimes not having test coverage.
- ASP.NET Core is moving toward native AOT compilation, which is not compatible with ASP.NET MVC.
Read on to find out how mitigate the most common concerns with adopting Minimal APIs.