liveBook · Manning

TryGetValue

As explained in Building Web APIs with ASP.NET Core

TryGetValue<T> is an IMemoryCache method that attempts to retrieve a value by key and reports whether a matching cache entry exists.

TryGetValue<T> attempts to retrieve a value from IMemoryCache by key. It returns true when an entry exists and conditionally places the retrieved value in an out parameter; otherwise, it returns false. section 8.3.3

A cache-or-query implementation uses it to:

  • Build a request-specific key by combining the input type name with its JSON serialization. section 8.3.3
  • Skip the database query when the cache contains a matching BoardGame[] value. section 8.3.3
  • Use the explicit generic type for clarity, although the compiler can infer it from the result variable. section 8.3.3

Verify a cache hit

Place a breakpoint on TryGetValue and another on the database-retrieval branch. Call the GET /BoardGames endpoint with default parameters: the first request should reach both points, while a repeated matching request should skip database retrieval when its entry remains cached. section 8.3.3

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Explains return values, the out parameter, generic inference, cache keys, and breakpoint-based verification.
Examples
Demonstrates typed BoardGame[] retrieval in BoardGamesController for repeated GET /BoardGames requests.
What it assumes
Assumes familiarity with C# generics, out parameters, JSON serialization, and EF Core query execution.
What you can do after
Diagnose cache hits and misses by tracing TryGetValue and the conditional database-retrieval branch.
How it connects
Connects IMemoryCache with JSON serialization, cache keys, EF Core, and HTTP response caching.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.