liveBook · Manning

Factory

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

A factory function is a function that creates and returns a configured object.

A factory function creates and returns a configured object or function. It separates the decision about what to create from the code that uses the result. section 5.4.3 section 9.6

In ASP.NET Core, factories support two closely related jobs:

  • An endpoint-filter factory examines an endpoint’s method information and returns a filter function tailored to that endpoint. section 5.4.3
  • A dependency-injection factory describes how to create a service, including services that are available only while the application is running. section 9.6
  • Prefer constructor injection over resolving services with GetService() or GetRequiredService() inside a factory when possible. section 9.6

One factory, several endpoint signatures

Adding AddEndpointFilterFactory(ValidationHelper.ValidateIdFactory) to both GET and POST endpoints lets one factory inspect each method signature and create a filter that locates the id parameter wherever it appears. section 5.4.3

Figure 5.10 A filter factory is a generalized way to add endpoint filters. The factory reads details about the endpoint, such as its method signature, and builds a filter function. This function is incorporated into the final filter pipeline for the endpoint. The build step means that a single filter factory can create filters for multiple endpoints with different method signatures.
CH05_F10_Lock3

The factory reads endpoint details, builds a filter function, and places that function into the endpoint’s final filter pipeline. section 5.4.3

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

How deep it goes
Explains endpoint inspection, filter emission, service lifetimes, and constructor-injection preference; defers endpoint metadata details.
Examples
Uses a fruit API’s ValidateId filter and lambda-created dependency-injection services as concrete examples.
What it assumes
Uses endpoint-handler parameters and registered services while introducing factory functions through small practical examples.
What you can do after
Apply it via ASP.NET Core to tailor endpoint filters and create registered services with chosen lifetimes.
How it connects
Connects endpoint filters with method signatures and dependency injection with service lifetimes and constructor injection.

Also explained in

Compare how 11 books explain factory →

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.