Thursday, June 2, 2022
HomeITUse logging and DI in minimal APIs in ASP.NET Core 6

Use logging and DI in minimal APIs in ASP.NET Core 6


ASP.NET Core 6 introduces a simplified internet hosting mannequin that can be utilized to implement light-weight APIs with minimal dependencies. These minimal APIs dramatically scale back the boilerplate code you should write to get your ASP.NET Core 6 purposes up and operating.

We mentioned methods to get began with minimal APIs in an earlier article. On this article we’ll discover extra superior features of minimal APIs together with implementing logging, studying from the configuration system, and utilizing dependency injection.

To work with the code examples offered on this article, it’s best to have Visible Studio 2022 put in in your system. In the event you don’t have already got a replica, you may obtain Visible Studio 2022 right here.

Create an ASP.NET Core minimal net API venture in Visible Studio 2022

First off, let’s create an ASP.NET Core venture in Visible Studio 2022. Following these steps will create a brand new ASP.NET Core Internet API 6 venture in Visible Studio 2022:

  1. Launch the Visible Studio 2022 IDE.
  2. Click on on “Create new venture.”
  3. Within the “Create new venture” window, choose “ASP.NET Core Internet API” from the record of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new venture” window, specify the title and site for the brand new venture.
  6. Optionally test the “Place answer and venture in the identical listing” test field, relying in your preferences.
  7. Click on Subsequent.
  8. Within the “Extra Data” window proven subsequent, uncheck the test field that claims “Use controllers…” since we’ll be utilizing minimal APIs on this instance. Depart the “Authentication Kind” as “None” (default).
  9. Be sure that the test containers “Allow Docker,” “Configure for HTTPS,” and “Allow Open API Help” are unchecked as we received’t be utilizing any of these options right here.
  10. Click on Create.

It will create a brand new ASP.NET Core 6 Internet API venture in Visible Studio 2022. We’ll use this venture to work with a minimal API within the subsequent sections of this text.

Run a minimal net API

You will get your minimal API working with just some strains of code:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Construct();
app.MapGet("https://www.infoworld.com/", () => "That is an instance of a minimal API");
app.Run();

Configure a number of ports for a minimal net API

The next code snippet illustrates how one can configure your minimal API to run on one particular port.

var app = WebApplication.Create(args);
app.MapGet("https://www.infoworld.com/", () => "Hi there World!");
app.Run("http://localhost:5178");

Once you run the applying and browse to this URL, it’s best to see the “Hi there World!” message displayed in your net browser.

You need to use a number of ports by including the URLs as proven within the following code snippet.

app.Urls.Add("http://localhost:5178");
app.Urls.Add("http://localhost:5179");

On this case, when you browse to any of those endpoints, the identical “Hi there World!” message shall be displayed.

You possibly can even learn the port from the atmosphere as proven within the code snippet given beneath.

var app = WebApplication.Create(args);
var port = Setting.GetEnvironmentVariable("PORT") ?? "5155";
app.MapGet("https://www.infoworld.com/", () => "Hi there World!");
app.Run($"http://localhost:{port}");

Use logging in a minimal net API

You can too use logging in your minimal APIs. Right here is how one can log information to the console utilizing Serilog:

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

You need to use Serilog for creating logs that persist software restarts as effectively. Serilog helps logging to a database, file, cloud storage, and different targets. The next code snippet illustrates how you should utilize Serilog in minimal APIs.

var builder = WebApplication.CreateBuilder(args);
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .WriteTo.File("logs.txt", rollingInterval: RollingInterval.Day)
    .CreateLogger();

The next code snippet exhibits how you should utilize logging in your minimal API.

app.MapGet("https://www.infoworld.com/", (ILoggerFactory loggerFactory) => {
    var logger = loggerFactory.CreateLogger("Begin");
    logger.LogInformation("Beginning...");
    return "Logging at work!";
});

Learn from the configuration system in a minimal API

You can too learn from the configuration system in your minimal API. The next code snippet exhibits how this may be achieved.

var app = WebApplication.Create(args);
var message = app.Configuration["TextMessage"] ?? "It is a default message.";
app.MapGet("https://www.infoworld.com/", () => message);
app.Run();

Use dependency injection in a minimal net API

If you need to make use of a HttpClient occasion to connect with a distant useful resource, you should utilize dependency injection as proven within the code snippet given beneath.

app.MapGet("https://www.infoworld.com/", (IHttpClientFactory httpClientFactory) => "Inside HttpGet technique");

Bear in mind so as to add HttpClient to the container utilizing the next code.

builder.Providers.AddHttpClient();

You can too make the most of dependency injection in a HttpPost technique. The code snippet beneath exhibits how one can move an occasion of IHttpClientFactory as a parameter to your HttpPost technique.

app.MapPost("https://www.infoworld.com/", (IHttpClientFactory httpClientFactory) =>
{
    var consumer = httpClientFactory.CreateClient();
    return Outcomes.Okay();
});

Inject a customized class in a minimal net API

You can too inject an occasion of a customized class in your minimal API. As an instance this, let’s implement two varieties: the IAuthorRepository interface and the AuthorRepository class. We’ll use these varieties to implement dependency injection in our minimal API.

Create a brand new file named IAuthorRepository.cs and insert the next code:

    public interface IAuthorRepository
    {
        public Listing<Creator> GetAuthors();
        public Creator GetAuthor(int id);
    }

The AuthorRepository class implements the IAuthorRepository interface as proven beneath.

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

Inject a customized interface in a minimal net API

The next code snippet illustrates how one can inject an occasion of the IAuthorRepository interface.

app.MapGet("api/writer/{id:int}", async (IAuthorRepository authorRepository, HttpContext httpContext) =>
{
    var id = int.Parse((string)httpContext.Request.RouteValues["id"]);
    var writer = authorRepository.GetAuthor(id);
    if (writer == null)
    {
        return Outcomes.NotFound();
    }
    return Outcomes.Okay(writer);
});

Lastly, .NET 6 features a nice new characteristic, world utilizing directives. To leverage world usings, create a brand new file named Usings.cs and transfer all your utilizing statements there. You need to use this characteristic along with your ASP.NET Core 6 or minimal APIs.

I’ll have extra to say about minimal APIs (comparable to working with safety and middleware) in a future publish right here.

Copyright © 2022 IDG Communications, Inc.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments