10. Dependency Injection in Minimal API: Logging in ASP.NET Core

ยท

3 min read

Minimal APIs in ASP.NET Core provide a simplified way to create HTTP APIs with minimal dependencies and setup. One of the powerful features of ASP.NET Core is its built-in Dependency Injection (DI) support. In this post, we'll explore how to use DI in a Minimal API to log messages using ILogger.

What is Dependency Injection?

Dependency Injection is a design pattern that allows an object to receive its dependencies from an external source rather than creating them itself. This promotes loose coupling and makes code more testable and maintainable.

In ASP.NET Core, services like logging, configuration, and database contexts are typically registered in the DI container and then injected into your components, such as controllers or minimal API handlers.

Setting Up a Minimal API

First, let's set up a basic Minimal API project. If you don't already have a project, you can create one using the .NET CLI:

dotnet new web -n MinimalApiDemo
cd MinimalApiDemo

Next, open the Program.cs file. This file is the entry point of your application and will contain the code for setting up the minimal API and dependency injection.

Creating the Coupon Model and Store

We'll start by defining a simple Coupon model and a static CouponStore to hold our data:

public class Coupon
{
    public int Id { get; set; }
    public string Code { get; set; }
    public int Discount { get; set; }
}

public static class CouponStore
{
    public static List<Coupon> couponList = new List<Coupon>
    {
        new Coupon { Id = 1, Code = "SAVE10", Discount = 10 },
        new Coupon { Id = 2, Code = "SAVE20", Discount = 20 }
    };
}

Setting Up Dependency Injection and Logging

In ASP.NET Core, logging is provided out-of-the-box and can be injected wherever it's needed. Hereโ€™s how you can set up a GET endpoint that uses ILogger to log messages.

Update your Program.cs with the following code:

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

var builder = WebApplication.CreateBuilder(args);

// Configure logging
builder.Services.AddLogging();

var app = builder.Build();

// Define the endpoint with logging
app.MapGet("/api/coupon", (ILogger<Program> _logger) => {
    _logger.Log(LogLevel.Information, "Getting all Coupons");
    return Results.Ok(CouponStore.couponList);
})
.WithName("GetCoupons")
.Produces<IEnumerable<Coupon>>(200);

app.Run();

Explanation

  1. Creating the Web Application Builder:

     var builder = WebApplication.CreateBuilder(args);
    

    This initializes a new WebApplicationBuilder instance, used to configure services and middleware for the application.

  2. Configuring Services:

     builder.Services.AddLogging();
    

    This adds logging services to the DI container. By default, ASP.NET Core includes several logging providers, such as Console and Debug.

  3. Building the Application:

     var app = builder.Build();
    

    This creates the WebApplication instance from the builder configuration.

  4. Defining the Endpoint:

     app.MapGet("/api/coupon", (ILogger<Program> _logger) => {
         _logger.Log(LogLevel.Information, "Getting all Coupons");
         return Results.Ok(CouponStore.couponList);
     })
     .WithName("GetCoupons")
     .Produces<IEnumerable<Coupon>>(200);
    
    • The MapGet method maps a GET request to the path /api/coupon and specifies a lambda function to handle the request.

    • The lambda function parameter (ILogger<Program> _logger) uses DI to get an instance of ILogger<Program>.

    • _logger.Log(LogLevel.Information, "Getting all Coupons"); logs an informational message.

    • return Results.Ok(CouponStore.couponList); returns a 200 OK response with the list of coupons.

    • .WithName("GetCoupons") names the endpoint "GetCoupons".

    • .Produces<IEnumerable<Coupon>>(200) indicates that the endpoint returns a 200 status code with a response body of type IEnumerable<Coupon>.

  5. Running the Application:

     csharpCopy codeapp.Run();
    

    This line runs the web application.

Conclusion

By leveraging Dependency Injection in your Minimal API, you can easily inject services like ILogger to keep your application well-structured and maintainable. Logging is just one example, but this pattern can be applied to other services, such as configuration, database contexts, and more.

Minimal APIs in ASP.NET Core offer a clean and efficient way to build HTTP APIs, and with DI, you can maintain clean separation of concerns and enhance the testability of your application.

Happy coding<๐ŸŒŽ>!

ย