liveBook · Manning

Code generation

As explained in ASP.NET Core in Action, 3e

Code generation is the automated production of source code or related artifacts from a higher-level description or specification.

Code generation turns an OpenAPI description into a strongly typed C# client. The generator reads documented endpoints and schemas, produces client code, and can rerun during builds when the local description changes. section 11.4

Figure 11.6 Visual Studio or a .NET tool downloads the OpenAPI description locally and installs the code-generation tool from NuGet. When your project builds, the generation tool reads the OpenAPI description and generates a C# class for interacting with the API.
CH11_F06_Lock3

The workflow connects the OpenAPI document, NuGet generator, build process, and generated C# API client. section 11.4

A practical OpenAPI client-generation workflow includes:

  • Download the API's OpenAPI JSON document into the consuming project. section 11.4
  • Configure an OpenAPI reference with NSwag, a namespace, and a generated client class name. section 11.4.1
  • Build the project to generate the client, updating package versions when Visual Studio adds outdated references. section 11.4.1
  • Use the generated methods to handle paths, parameters, serialization, deserialization, and error status codes without repeating that boilerplate. section 11.4.3
  • Improve generated method names by assigning endpoint names that become OpenAPI OperationIds. section 11.4.3

Calling a generated client

Create a FruitClient with an HttpClient, call FruitPOSTAsync to create a fruit, then call FruitGETAsync to retrieve it. The generated client performs the HTTP details. section 11.4.3

Generation is convenient but opinionated. Exception-based error handling, duplicated types from separate OpenAPI documents, awkward names, and unsupported specification features can make a handwritten client simpler. section 11.6.2 section 11.6.3

How ASP.NET Core in Action, 3e covers it

How deep it goes
Details setup, build integration, client usage, naming, customization, and tradeoffs without explaining generator internals.
Examples
Uses a FruitClient to create and retrieve fruit through generated asynchronous methods.
What it assumes
Assumes an OpenAPI-described API and a C# project; teaches the generation workflow from the project-reference setup onward.
What you can do after
Build and apply an NSwag-generated C# client for an OpenAPI-described API.
How it connects
Connects OpenAPI, NSwag, Visual Studio, .NET tools, NuGet, serialization, and API clients.

Also explained in

Compare how 17 books explain code generation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.