In ASP.NET Core 10, why create a custom bookings metric through IMeterFactory rather than a static Meter, and how does it reach the exporter?
answer
- the host already registered it
- Meter.Scope ties meter to container
- cached by name, version and tags
- singleton class holds the instruments
- AddMeter subscribes the provider
basics
~20 sIMeterFactory, registered by the host, creates meters tied to the DI container: cached per name, disposed with the container, and distinguishable per host in tests. A singleton creates the instruments once, and WithMetrics(m => m.AddMeter("Airline.Booking")) exports them.
solid answer
~40 sThe generic host registers `IMeterFactory` for every ASP.NET Core app, and the framework creates its own meters through it. I inject it into a singleton `BookingMetrics` class, call `meterFactory.Create("Airline.Booking")` once, and create the instruments in the constructor, for example `CreateCounter<long>("airline.bookings.completed")` and `CreateHistogram<double>("airline.checkout.duration", unit: "s")`. The factory sets the meter's `Scope` to itself, returns the same meter for the same name, version and tags, and disposes its meters when the container is disposed; calling `Dispose` on such a meter does nothing. A static `Meter` is process-wide, so two `WebApplicationFactory` hosts in one test run would share its measurements; with the factory, a test can listen only to its own host, for example with `MetricCollector<T>`. Nothing is exported until the meter provider subscribes with `AddMeter("Airline.Booking")`.
code
csharp · 25 linesusing System.Diagnostics.Metrics;
public sealed class BookingMetrics
{
private readonly Counter<long> _completed;
private readonly Histogram<double> _checkout;
public BookingMetrics(IMeterFactory meterFactory)
{
var meter = meterFactory.Create("Airline.Booking");
_completed = meter.CreateCounter<long>("airline.bookings.completed", unit: "{booking}");
_checkout = meter.CreateHistogram<double>("airline.checkout.duration", unit: "s");
}
public void BookingCompleted(string channel) =>
_completed.Add(1, new KeyValuePair<string, object?>("airline.channel", channel));
public void RecordCheckout(TimeSpan elapsed) => _checkout.Record(elapsed.TotalSeconds);
}
// Program.cs
builder.Services.AddSingleton<BookingMetrics>();
builder.Services.AddOpenTelemetry()
.WithMetrics(m => m.AddAspNetCoreInstrumentation().AddMeter("Airline.Booking"))
.UseOtlpExporter();go deeper
Know that custom metrics come from a Meter's instruments and need AddMeter with the same name before anything is exported.
Show the singleton metrics class built from IMeterFactory, with a Counter<long> and a seconds-based Histogram<double>, and its AddMeter registration.
Explain Meter.Scope, caching and disposal by the container, why a static Meter leaks across test hosts, and how MetricCollector<T> scoped to a factory isolates assertions.
Govern metric names, units and allowed tag values across services so dashboards aggregate cleanly and tag cardinality stays within what the backend can afford.
## The goal The airline wants two business metrics from **booking-api**: how many bookings complete, and how long checkout takes. Both should land in the same OTLP pipeline as ASP.NET Core's built-in request metrics. In .NET a metric is recorded through an **instrument** (such as `Counter<T>` or `Histogram<T>`) that belongs to a **`Meter`**, a named group of instruments. The question is who creates and owns that `Meter`. ## Two ways to get a `Meter` | | `static readonly Meter Meter = new("Airline.Booking")` | `IMeterFactory.Create("Airline.Booking")` | |---|---|---| | Lifetime | the whole process | the DI container that owns the factory | | Disposal | your job, usually never | the factory disposes its meters when the container is disposed | | `Meter.Scope` | `null` | the factory instance | | Several hosts in one process | all share one meter and its measurements | each host has its own meter | | Repeated `Create` with the same name, version and tags | n/a | returns the cached meter | The factory's meters also ignore `Dispose()` calls from your code: the override is a no-op, so a careless `using` cannot break other consumers of the same meter. ## Where `IMeterFactory` comes from You do not register it. The generic host calls `services.AddMetrics()` while building, and the ASP.NET Core web host does the same, so `IMeterFactory` is a singleton in every ASP.NET Core 10 app. ASP.NET Core's own metrics use it: the hosting layer creates its `Microsoft.AspNetCore.Hosting` meter with `meterFactory.Create(...)`. ## The pattern 1. **Write a metrics class** that takes `IMeterFactory` and creates the meter and its instruments in its constructor. 2. **Register it as a singleton**, so the instruments are created once and every request records into the same objects. 3. **Expose intent-revealing methods** (`BookingCompleted(channel)`, `RecordCheckout(seconds)`) instead of leaking instruments to handlers. 4. **Subscribe the SDK** with `WithMetrics(m => m.AddMeter("Airline.Booking"))` in `Program.cs`. Instrument choices for the scenario: - `Counter<long>` named `airline.bookings.completed` with unit `{booking}`, tagged with a small set such as the sales channel. - `Histogram<double>` named `airline.checkout.duration` with unit `s`, matching how ASP.NET Core reports `http.server.request.duration` in seconds. - Tags come from a fixed, small set of values. A booking reference or passenger id as a tag creates one time series per value and swamps the backend. ## Why the scope matters in tests Integration tests often start several hosts with `WebApplicationFactory<Program>` in one process, sometimes in parallel. With a static `Meter`, every listener in the process sees measurements from every host, and a test asserting "one booking completed" fails intermittently. With `IMeterFactory`, each host's meters carry that host's factory as their `Scope`. The **Microsoft.Extensions.Diagnostics.Testing** package's `MetricCollector<T>` has a constructor taking `(object? meterScope, string meterName, string instrumentName)`, so a test resolves its own host's `IMeterFactory`, passes it as the scope, acts, and reads `GetMeasurementSnapshot()` with no cross-talk. ## How it reaches the exporter - `AddMeter("Airline.Booking")` tells the OpenTelemetry meter provider to enable instruments from meters with that name; wildcards such as `"Airline.*"` are accepted. - The provider aggregates the measurements (sums for counters, bucketed distributions for histograms) and the exporter, for example `UseOtlpExporter()`, ships them on its collection interval. - Without `AddMeter`, the instruments stay disabled and `Add`/`Record` calls cost very little; no error is raised. ## Recording from a handler A Minimal API handler declares `BookingMetrics` as a parameter and the container injects the singleton. The handler starts a `Stopwatch` (or reads `TimeProvider` timestamps), completes the booking, then calls `metrics.BookingCompleted("web")` and `metrics.RecordCheckout(elapsed)`. Because the instruments are thread-safe and owned by the singleton, concurrent requests record into them without locks of your own. Keep the call sites thin: the handler states *what* happened, and the metrics class decides the instrument names, units and tags. That also makes renaming a metric a one-file change instead of a search through every handler. ## Common mistakes - Registering the metrics class as **scoped or transient**, which re-runs the constructor and re-creates instruments per request. - Creating meters with `new Meter(...)` inside request code. - Assuming the built-in `AddAspNetCoreInstrumentation()` also picks up custom meters; it lists only the framework's meter names.
- Does a meter created by IMeterFactory need a using statement?No. The factory owns its meters and disposes them when the DI container is disposed. The meter's own `Dispose` override is a no-op, so a `using` around it would do nothing, and code that holds instruments should simply live as a singleton beside the factory.
- Why must the BookingMetrics class be a singleton?Its constructor creates the instruments. As a singleton that happens once, and every request records into the same `Counter<long>` and `Histogram<double>`. Scoped or transient registration would rebuild the instruments per resolution, wasting work and listener bookkeeping for something meant to exist once per app.
Meters from IMeterFactory are like key cards issued by a hotel's front desk: the desk keeps ownership and deactivates every card at checkout, a guest dropping a card in the bin does not deactivate it, and each hotel's cards open only its own rooms. A static Meter is one master key shared by every hotel in the chain.
- You must register IMeterFactory yourself with AddMetrics in every ASP.NET Core app.
- Wrap a meter from IMeterFactory in using so it is released after each request.
- A static Meter is isolated per WebApplicationFactory host, so tests cannot see each other's measurements.
- AddAspNetCoreInstrumentation() also exports custom meters created through IMeterFactory.
- Booking ids are good metric tags because they make each measurement traceable.