SoFunction
Updated on 2025-04-07

Detailed explanation of the use of logs and DI examples in Core 6 Minimum API

Using logs and DI in Core 6's Minimum API

How to implement logs in Core 6's minimum API, read from the configuration system, and use dependency injection

Core 6 introduces a simplified managed model that can be used to implement lightweight APIs with minimal dependencies. These minimal APIs greatly reduce the template code you need to write to get your Core 6 application up and running.

We were in the pastarticleHow to get started with the minimum API is discussed in this article. In this article, we will explore more advanced aspects of minimizing APIs, including implementing logs, reading from configuration systems, and using dependency injection.

CI/CD? Continuous Integration and Continuous Delivery Explanation

Also on InfoWorld. What is CI/CD? Continuous Integration and Continuous Delivery Explanation

To use the code examples provided in this article, you should have Visual Studio 2022 installed on your system. If you don't have a copy yet, you canDownload Visual Studio 2022 here

Create a Core minimum web API project in Visual Studio 2022

First, let's create a Core project in Visual Studio 2022. Following these steps will create a new Core Web API 6 project in Visual Studio 2022:

  • Start Visual Studio 2022 IDE
  • Click "Create a new project"
  • In the Create New Project window, select Core Web API from the displayed template list;
  • Click "Next"
  • In the Configure Your New Project window, specify the name and location of the new project
  • Depending on your preferences, you can select the "Put Solution and Project in the same directory" check box
  • Click "Next"
  • In the "Add Information" window that appears next, uncheck the "Use Controller..." checkbox because in this example we will use the smallest API. Leave "Verification Type" as "None" (default)
  • Make sure the check boxes for "Enable Docker", "Configure for HTTPS" and "Enable Open API Support" are not selected, as we won't use any of these features here
  • Click Create

This will create a new Core 6 Web API project in Visual Studio 2022. We will use this project in subsequent chapters of this article to handle a minimal API.

Run a minimal network API

You can just write a few lines of code to get your minimal API to work:

var builder = (args);
var app = ();
("/", () => "This is an example of a minimal API");
();

Configure multiple ports for a minimal network API

The following code snippet illustrates how you configure your minimum API to run on a specific port:

var app = (args);
("/", () => "Hello World!");
("http://localhost:5178");

When you run the application and browse to this URL, you should see the "Hello World!" message displayed in your web browser.

You can use multiple ports by adding URLs, as shown in the following code snippet:

("http://localhost:5178");
("http://localhost:5179");

In this case, if you browse to any of these endpoints, the same "Hello World!" message will be displayed.

You can even read the port from the environment as shown in the code snippet given below:

var app = (args);
var port = ("PORT") ?? "5155";
("/", () => "Hello World!");
($"http://localhost:{port}");

Using logging in minimal web API

You can also use logs in your minimal API. Here is how you can use Serilog to log data to the console:

var logger = new LoggerConfiguration()
    .()
    .CreateLogger();

You can use Serilog to create logs so that the application can continue when restarting. Serilog supports logging to databases, files, cloud storage and other targets. The following code snippet illustrates how you use Serilog in a minimal API:

var builder = (args);
 = new LoggerConfiguration()
    .()
    .("", rollingInterval: )
    .CreateLogger();

The following code snippet illustrates how you use logging in a minimal API:

("/", (ILoggerFactory loggerFactory) => {
    var logger = ("Start");
    ("Starting...");
    return "Logging at work!";
});

Read from the configuration system in a minimal API

You can also read from the configuration system in your smallest API. The following code snippet shows how to implement this:

var app = (args);
var message = ["TextMessage"] ?? "This is a default message.";
("/", () => message);
();

Using dependency injection in minimal network API

If you want to use an HttpClient instance to connect to a remote resource, you can use dependency injection as shown in the code snippet given below:

("/", (IHttpClientFactory httpClientFactory) => "Inside HttpGet method");

Remember to add HttpClient to the container using the following code:

();

You can also take advantage of dependency injection in the HttpPost method. The following code snippet shows how you pass an instance of IHttpClientFactory as a parameter to your HttpPost method:

("/", (IHttpClientFactory httpClientFactory) =>
{
    var client = ();
    return ();
});

Inject a custom class into a minimal web API

You can also inject an instance of a custom class into your minimal API. To illustrate this, we implement two types: the IAuthorRepository interface and the AuthorRepository class. We will use these types to implement dependency injection in our minimal API.

Create a new file named and insert the following code:

   public interface IAuthorRepository
    {
        public List<Author> GetAuthors();
        public Author GetAuthor(int id);
    }

The AuthorRepository class implements the IAuthorRepository interface, as shown in the figure below:

 public class AuthorRepository: IAuthorRepository
    {
        private readonly List<Author> _authors;
        public AuthorRepository()
        {
            _authors = new List<Author>
            {
                new Author
                {
                    Id = 1,
                    FirstName = "Joydip",
                    LastName = "Kanjilal"
                },
                new Author
                {
                    Id = 2,
                    FirstName = "Steve",
                    LastName = "Smith"
                },
                new Author
                {
                    Id = 3,
                    FirstName = "Julie",
                    LastName = "Lerman"
                },
                new Author
                {
                    Id = 4,
                    FirstName = "Simon",
                    LastName = "Bisson"
                }
            };
        }
        public List<Author> GetAuthors()
        {
            return _authors;
        }
        public Author GetAuthor(int id)
        {
            return _authors.Find(x=>  == id);
        }
    }

Inject a custom interface into the smallest network API

The following code snippet illustrates how you inject an instance of the IAuthorRepository interface:

("api/author/{id:int}", async (IAuthorRepository authorRepository, HttpContext httpContext) =>
{
    var id = ((string)["id"]);
    var author = (id);
    if (author == null)
    {
        return ();
    }
    return (author);
});

Finally, .NET 6 includes a great new feature-Global usage instructions. To take advantage of global usage, create a new file named and move all your usage statements there. You can use this feature in your Core 6 or the smallest API. For more information about Core 6 API log DI, please follow my other related articles!