February 4, 2023

Mulvihill-technology

For computer aficionados

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

ASP.Net Core 6 introduces a simplified internet hosting design that can be utilised to implement lightweight APIs with nominal dependencies. These small APIs considerably reduce the boilerplate code you want to publish to get your ASP.Net Core 6 purposes up and functioning.

We reviewed how to get begun with nominal APIs in an previously report. In this write-up we’ll investigate more innovative facets of minimal APIs like employing logging, studying from the configuration program, and applying dependency injection.

To perform with the code illustrations supplied in this posting, you ought to have Visual Studio 2022 set up in your method. If you never now have a duplicate, you can down load Visible Studio 2022 here.

Build an ASP.Web Main nominal net API job in Visual Studio 2022

Initially off, let us produce an ASP.Net Core task in Visible Studio 2022. Pursuing these techniques will make a new ASP.Internet Main Website API 6 undertaking in Visual Studio 2022:

  1. Start the Visual Studio 2022 IDE.
  2. Simply click on “Create new task.”
  3. In the “Create new project” window, select “ASP.Internet Core World wide web API” from the list of templates shown.
  4. Simply click Future.
  5. In the “Configure your new project” window, specify the identify and area for the new job.
  6. Optionally check the “Place answer and challenge in the exact directory” test box, dependent on your choices.
  7. Click on Next.
  8. In the “Additional Information” window revealed upcoming, uncheck the check box that states “Use controllers…” due to the fact we’ll be utilizing small APIs in this case in point. Depart the “Authentication Type” as “None” (default).
  9. Make sure that the test packing containers “Enable Docker,” “Configure for HTTPS,” and “Enable Open API Support” are unchecked as we won’t be working with any of those attributes right here.
  10. Click Develop.

This will generate a new ASP.Web Main 6 Website API venture in Visible Studio 2022. We’ll use this venture to function with a negligible API in the subsequent sections of this short article.

Operate a nominal website API

You can get your small API doing work with just a few traces of code:

var builder = WebApplication.CreateBuilder(args)
var app = builder.Establish()
application.MapGet("https://www.infoworld.com/", () => "This is an illustration of a nominal API")
app.Operate()

Configure multiple ports for a minimum net API

The following code snippet illustrates how you can configure your minimal API to operate on a single certain port.

var application = WebApplication.Develop(args)
application.MapGet("https://www.infoworld.com/", () => "Hi there Planet!")
app.Operate("http://localhost:5178")

When you run the application and browse to this URL, you ought to see the “Hello Environment!” concept displayed in your world wide web browser.

You can use various ports by including the URLs as revealed in the adhering to code snippet.

app.Urls.Incorporate("http://localhost:5178")
application.Urls.Incorporate("http://localhost:5179")

In this case, if you browse to any of these endpoints, the same “Hello World!” concept will be exhibited.

You can even read the port from the atmosphere as proven in the code snippet given down below.

var application = WebApplication.Produce(args)
var port = Ecosystem.GetEnvironmentVariable("PORT") ?? "5155"
application.MapGet("https://www.infoworld.com/", () => "Hello Entire world!")
app.Run($"http://localhost:port")

Use logging in a small net API

You can also use logging in your nominal APIs. In this article is how you can log data to the console applying Serilog:

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

You can use Serilog for developing logs that persist application restarts as effectively. Serilog supports logging to a database, file, cloud storage, and other targets. The subsequent code snippet illustrates how you can use Serilog in negligible APIs.

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

The subsequent code snippet displays how you can use logging in your minimal API.

app.MapGet("https://www.infoworld.com/", (ILoggerFactory loggerFactory) => 
    var logger = loggerFactory.CreateLogger("Get started")
    logger.LogInformation("Beginning...")
    return "Logging at function!"
)

Browse from the configuration program in a nominal API

You can also read from the configuration method in your nominal API. The subsequent code snippet reveals how this can be reached.

var application = WebApplication.Create(args)
var message = application.Configuration["TextMessage"] ?? "This is a default information."
application.MapGet("https://www.infoworld.com/", () => concept)
app.Operate()

Use dependency injection in a nominal world-wide-web API

If you would like to use a HttpClient occasion to link to a distant resource, you can use dependency injection as shown in the code snippet offered beneath.

application.MapGet("https://www.infoworld.com/", (IHttpClientFactory httpClientFactory) => "Within HttpGet method")

Recall to include HttpClient to the container making use of the subsequent code.

builder.Providers.AddHttpClient()

You can also get advantage of dependency injection in a HttpPost strategy. The code snippet below reveals how you can go an occasion of IHttpClientFactory as a parameter to your HttpPost method.

application.MapPost("https://www.infoworld.com/", (IHttpClientFactory httpClientFactory) =>

    var consumer = httpClientFactory.CreateClient()
    return Outcomes.Ok()
)

Inject a tailor made class in a minimal internet API

You can also inject an occasion of a custom made course in your small API. To illustrate this, let us implement two types: the IAuthorRepository interface and the AuthorRepository class. We’ll use these varieties to apply dependency injection in our minimum API.

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

    public interface IAuthorRepository
   
        community List GetAuthors()
        general public Creator GetAuthor(int id)
   

The AuthorRepository class implements the IAuthorRepository interface as shown beneath.

 public course AuthorRepository: IAuthorRepository
   
        non-public readonly Record _authors
        public AuthorRepository()
       
            _authors = new List
           
                new Author
               
                    Id = 1,
                    FirstName = "Joydip",
                    LastName = "Kanjilal"
                ,
                new Author
               
                    Id = 2,
                    FirstName = "Steve",
                    LastName = "Smith"
                ,
                new Writer
               
                    Id = 3,
                    FirstName = "Julie",
                    LastName = "Lerman"
                ,
                new Writer
               
                    Id = 4,
                    FirstName = "Simon",
                    LastName = "Bisson"
               
           
       
        public List GetAuthors()
       
            return _authors
       
        public Creator GetAuthor(int id)
       
            return _authors.Locate(x=> x.Id == id)
       
   

Inject a personalized interface in a nominal world-wide-web API

The pursuing code snippet illustrates how you can inject an instance of the IAuthorRepository interface.

app.MapGet("api/writer/id:int", async (IAuthorRepository authorRepository, HttpContext httpContext) =>

    var id = int.Parse((string)httpContext.Ask for.RouteValues["id"])
    var author = authorRepository.GetAuthor(id)
    if (writer == null)
   
        return Effects.NotFound()
   
    return Success.Ok(writer)
)

At last, .Web 6 incorporates a wonderful new attribute, global applying directives. To leverage international usings, generate a new file named Usings.cs and move all of your utilizing statements there. You can use this characteristic with your ASP.Internet Main 6 or minimal APIs.

I’ll have a lot more to say about nominal APIs (these types of as doing work with stability and middleware) in a upcoming put up below.

Copyright © 2022 IDG Communications, Inc.