Enhancing ASP.NET Core Minimal APIs with Dependency Injection and Swagger

In our previous post, we introduced Minimal APIs in .NET 6 — a new way to build lightweight HTTP APIs without the overhead of MVC. If you’re experimenting with them, one of the first questions you might have is:

How do I use services and generate OpenAPI docs like I would in a traditional app?

Good news: you can! Even though Minimal APIs are, well, minimal — they fully support dependency injection (DI) and Swagger/OpenAPI through the standard ASP.NET Core extensions.

Let’s walk through how to integrate both.


🧱 1. Injecting Services into Minimal APIs

Just like with controllers, you can use constructor injection — but in Minimal APIs, DI works directly via handler parameters.

🧪 Step-by-Step Example

Let’s say you have a simple IProductService:

public interface IProductService
{
    IEnumerable<string> GetAll();
}

public class ProductService : IProductService
{
    public IEnumerable<string> GetAll() => new[] { "Apple", "Banana", "Orange" };
}

Now register it in Program.cs:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<IProductService, ProductService>();

var app = builder.Build();

app.MapGet("/products", (IProductService service) =>
{
    return service.GetAll();
});

app.Run();

✅ That’s it. ASP.NET Core will resolve IProductService from the container and pass it in when the endpoint is called.


📘 2. Adding Swagger Support

You might assume Swagger is only for full MVC apps. Nope! Minimal APIs can use it just as easily with Swashbuckle.AspNetCore.

🛠 Step-by-Step:

  1. Add the NuGet package:
dotnet add package Swashbuckle.AspNetCore
  1. Configure Swagger in Program.cs:
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
  1. Enable it in the app:
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

Now, any endpoint you define with Minimal APIs will be picked up by Swagger, and you’ll get auto-generated docs at /swagger.


✨ Optional: Describe Parameters and Responses

You can also annotate your endpoints with metadata using .WithName().WithSummary(), and .Produces():

app.MapGet("/products", (IProductService service) =>
{
    return service.GetAll();
})
.WithName("GetProducts")
.WithSummary("Returns a list of all products.")
.Produces<IEnumerable<string>>(StatusCodes.Status200OK);

This metadata will appear in your Swagger UI and make your docs more usable for teams and consumers.


🧪 Bonus: Using [FromServices] for Optional Injection

Want to optionally pull something from DI? You can also use [FromServices]:

app.MapGet("/greet", ([FromServices] IHostEnvironment env) =>
{
    return $"Running in {env.EnvironmentName}";
});

✅ Recap

Minimal APIs are more powerful than they look. In just a few lines:

  • You can inject services from the DI container directly into endpoints.
  • You can generate full Swagger documentation using Swashbuckle.
  • You don’t need to compromise on developer experience.

We’re just scratching the surface. Minimal APIs are shaping up to be a fantastic option for small services, internal tools, or even production apps with focused endpoints.


Let me know if you’d like to go deeper into:

  • Validation and model binding
  • Authentication and authorization
  • Testing Minimal APIs
  • Using Filters or Middleware patterns

Thanks for reading!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *