Volume 1 · Chapter 7 — Modern C# and .NET Foundations
Reflection and Metadata
7.1 Introduction
Reflection is the runtime ability to inspect assemblies, types, methods, properties, and attributes dynamically - and to invoke them without knowing them at compile time. It is the mechanism behind much of what makes .NET frameworks feel magical: dependency-injection containers discovering constructors, ORMs mapping entities, serializers reading properties, test runners finding tests, and model binders populating objects. Understanding reflection - and its cost - is essential, because so much enterprise framework behavior is powered by runtime metadata discovery.
7.2 Metadata and Assembly Loading
Every .NET assembly contains rich metadata describing its types and members - the manifest, type definitions, methods, properties, and attributes - which the CLR uses to understand code without executing it. The runtime loads assemblies lazily when types they contain are first needed, reading that metadata to build the runtime type information reflection exposes.
flowchart TB ASM["Assembly"] --> Man["Manifest"] ASM --> Types["Type definitions"] Types --> Meth["Methods"] Types --> Prop["Properties"] Types --> Attr["Attributes"] Meta["Metadata"] -.-> Refl["Reflection reads this at runtime"]
7.3 Reflection APIs and Attributes
Reflection lets you inspect a type’s members at runtime. Attributes attach declarative metadata to code that frameworks read to modify behavior without changing your logic - routing, validation, serialization, and ORM mappings are all attribute-driven.
Type type = typeof(Customer);
foreach (var prop in type.GetProperties())
Console.WriteLine($"{prop.Name}: {prop.PropertyType.Name}");
// Attributes are metadata read by frameworks:
[ApiController, Route("customers")]
public class CustomersController : ControllerBase
{
[HttpGet("{id:guid}")] public IActionResult Get(Guid id) => Ok();
}
7.4 Dynamic Invocation and Plugins
Reflection can invoke methods whose name or type is unknown at compile time, and load external assemblies at runtime - the basis of plugin architectures where new capabilities are added without recompiling the host. Modern .NET usesAssemblyLoadContextfor isolated, unloadable plugin loading.
var ctx = new AssemblyLoadContext("plugin", isCollectible: true);
var asm = ctx.LoadFromAssemblyPath(pluginPath);
var pluginType = asm.GetTypes().First(t => typeof(IPlugin).IsAssignableFrom(t));
var plugin = (IPlugin)Activator.CreateInstance(pluginType)!;
plugin.Run();
7.5 The Cost of Reflection - and Source Generators
Reflection is powerful but slower than direct calls because runtime discovery and invocation add overhead, and it defeats trimming and Native AOT (the linker cannot tell which types reflection will use). The modern alternative issource generators, which do at compile time what reflection does at runtime - emitting code that is faster, allocation-free, trimmable, and AOT-friendly. System.Text.Json’s source generator is the canonical example.
| Reflection | Source Generators |
|---|---|
| Runtime discovery and invocation | Compile-time code generation |
| Flexible and dynamic | Faster, no startup reflection cost |
| Defeats trimming / AOT | Trimmable and AOT-compatible |
How does dependency injection use reflection?
Most DI containers use reflection to discover and satisfy dependencies automatically. When you register a service and the container needs to create it, it uses reflection to inspect the type’s constructor(s), determine the parameter types (the dependencies), recursively resolve each of those from the registrations, and then invoke the constructor with the resolved instances to build the object graph - all without you writing the wiring by hand. Reflection is also how the container reads metadata like attributes and discovers types during assembly scanning (for example, finding all controllers or all implementations of an interface to register them). This runtime inspection is what makes constructor injection so convenient - you declare dependencies as constructor parameters and the container figures out how to provide them. The trade-off is the runtime cost of reflection (mitigated by the container caching the reflected metadata after first use) and that heavy assembly scanning can slow startup. For performance- or AOT-sensitive scenarios, some containers and the framework increasingly use source generators to do this discovery at compile time instead. But fundamentally, classic DI’s ability to auto-wire object graphs from constructor signatures is powered by reflection.
What are attributes and how do frameworks use them?
Attributes are a way to attach declarative metadata to code elements - classes, methods, properties, parameters, assemblies - which frameworks and tools read (via reflection) to change behavior without you writing imperative logic. An attribute like[HttpGet("{id}")]or[Required]or[JsonPropertyName("id")]doesn’t do anything by itself; it records metadata that a framework inspects at runtime (or a source generator at compile time) and acts on. ASP.NET Core reads routing and model-binding attributes to map requests to actions and validate input; Entity Framework reads mapping attributes to configure how entities map to tables and columns; serializers read attributes to control JSON shape; validation frameworks read data-annotation attributes; test frameworks read attributes to discover and configure tests. The value is declarative configuration - you express intent as metadata right where it applies, and the framework interprets it - which keeps your code focused on logic while cross-cutting configuration lives in attributes. Frameworks discover and read attributes through reflection (or, increasingly, source generation), so attributes are essentially the metadata channel through which you configure framework behavior declaratively.
Why is reflection slower than direct calls, and how do you mitigate it?
Reflection is slower because it does at runtime what compiled code does ahead of time: it looks up metadata, performs type and access checks, and invokes members indirectly rather than through a direct, JIT-optimized call. A reflective method invocation involves resolving theMethodInfo, boxing/unboxing arguments into anobject[], security/validation checks, and an indirect dispatch - all far more expensive than a direct call the JIT can inline. Repeated type discovery (scanning assemblies, enumerating members) adds startup and per-call cost, and reflection allocates. To mitigate it: cache the reflected metadata (MethodInfo,PropertyInfo, attribute lookups) so discovery happens once, not per call; avoid repeated scanning by building lookups upfront; compile reflected access into fast delegates (for example via compiled expression trees orDynamicMethod), which turns repeated reflective calls into near-direct-call speed after a one-time setup cost; and, best of all for performance- and AOT-sensitive code, replace reflection with source generators that emit the equivalent code at compile time, eliminating the runtime cost entirely. So the mitigations are, in order: cache metadata, compile to delegates, or move the work to compile time with source generation - which is why modern high-performance libraries increasingly favor source generators over reflection.
When would you replace reflection with source generators, and what do you gain?
I replace reflection with source generators when startup time, runtime performance, allocations, or Native AOT / trimming compatibility matter - which is increasingly common in cloud-native, serverless, and high-throughput services. Reflection does its work at runtime, which costs CPU on first use, adds startup latency (especially with assembly scanning), allocates, and - critically - defeats the trimmer and is incompatible with Native AOT, because the linker cannot statically determine which types and members reflection will touch, so it must keep everything (bloating size) or the app breaks under trimming/AOT. A source generator does the equivalent work at compile time, emitting concrete, statically-analyzable code: there is no runtime reflection cost, startup is faster, the generated code is allocation-lean and can be inspected and debugged, and it is fully trimmable and AOT-compatible because the usage is explicit in the generated source. The canonical examples are System.Text.Json’s source generator (faster, AOT-ready JSON) andLoggerMessagefor logging. So I’d move to source generators for serialization, DI registration, logging, mapping, and similar reflection-heavy concerns when I’m targeting AOT, minimizing cold-start (serverless/containers), or optimizing hot paths, gaining faster startup, better throughput, smaller trimmed binaries, and AOT compatibility. The trade-off is more build-time complexity and less runtime dynamism, so for flexible, non-performance-critical scenarios plain reflection remains fine - but for the performance and AOT-sensitive cases, source generation is the clear modern choice.
7.6 Production Scenario
A large API platform has slow startup because hundreds of assemblies are scanned via reflection to discover services and controllers, and it is targeting Native AOT for faster cold starts. The team caches reflected metadata, reduces assembly scanning, and moves serialization and part of the DI registration to source generators - cutting startup time and making the app trimmable and AOT-compatible.
Chapter Revision Notes
- Metadata describes .NET types at runtime and enables reflection.
- Reflection powers DI, ORMs, serializers, and plugin systems via runtime discovery.
- Attributes attach declarative metadata that frameworks read to change behavior.
- Reflection has real runtime cost and defeats trimming/AOT.
- Source generators move that work to compile time - faster, trimmable, AOT-friendly.