liveBook · Manning

Generics

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

A generic method is a method defined with type parameters that can operate on arguments or return values of specified types.

Generics let one type describe reusable behavior for multiple types. An open generic, such as Repository<T>, keeps T unspecified until the dependency-injection container resolves a concrete request. section 9.2

In dependency injection, requesting IRepository<Customer> can produce DbRepository<Customer>. Register open generic implementations with the typeof overload rather than the usual generic registration methods. section 9.2

Register an open generic

builder.Services.AddScoped(typeof(IRepository<>), typeof(DbRepository<>)); This registration tells the container to pair each requested IRepository<T> with the matching DbRepository<T>. section 9.2

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

How deep it goes
Explains open generic resolution and registration syntax, but stops short of implementing a generic repository.
Examples
Uses Repository<T>, IRepository<Customer>, DbRepository<Customer>, and an AddScoped typeof registration.
What it assumes
Assumes familiarity with dependency-injection service registration and interfaces, while illustrating generic type parameters through repository examples.
What you can do after
Operate/configure dependency injection by registering open generic interfaces and implementations with IServiceCollection.
How it connects
Connects generics with dependency injection, constructor injection, service lifetimes, repositories, and IServiceCollection.

Also explained in

Compare how 20 books explain generics →

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.