Skip to content

fix(aspnetcore): start the SDK when the host starts, not on the first request - #5721

Merged
jamescrosswell merged 1 commit into
mainfrom
fix/aspnetcore-init-on-start
Oct 13, 2026
Merged

jamescrosswell merged 1 commit into
mainfrom
fix/aspnetcore-init-on-start

Conversation

@ric-oliv

Copy link
Copy Markdown
Member

In some ASP.NET Core apps, UseSentry started the SDK on the first request instead of when the host started. Until that request, SentrySdk.IsEnabled was false, so unhandled exceptions, Serilog events and SentrySdk.CaptureException calls didn't reach Sentry. An app that never got a request never started the SDK. It affected apps that do both of these:

  • Replace or clear the logger providers, for example with Serilog's UseSerilog() or builder.Logging.ClearProviders().
  • Run without Sentry's tracing middleware, because they don't use endpoint routing, call options.UseOpenTelemetry(), or set AutoRegisterTracing = false.

#1979 caused this in 3.23.0. It made SentryMiddleware an IMiddleware, which ASP.NET Core resolves when a request arrives. Before, the middleware's constructor took Func<IHub> and ran while ASP.NET Core built the pipeline, and that started the SDK. UseSentry now resolves Func<IHub> itself, right before it adds the middleware, so the SDK starts in StartAsync() again. It does this after it installs the diagnostic logger, so with Debug on, the startup messages go to the app's logs.

Apps that already started the SDK in Build() or StartAsync() see no change, and InitializeSdk = false still keeps the SDK off. Two things move to startup in the affected apps:

  • A missing or invalid DSN now makes host start throw. Before, the app started and answered every request with a 500. Apps with the default logger providers already throw in Build().
  • If a Serilog sink or a SentrySdk.Init call also starts the SDK, UseSentry now replaces that hub at startup instead of on the first request.

Hosted services still start before ASP.NET Core builds the pipeline, so their StartAsync runs before the SDK starts in these apps.

#1979 added a request to WebHost_SdkStartedViaStartupFilter_DisableSdkOnShutdown "to make sure Sentry is initialized", which hid the regression. The test now checks SentrySdk.IsEnabled right after the host starts. New tests cover an invalid DSN, InitializeSdk = false, and the order of the diagnostic logger and the SDK start in UseSentry.

Since #1979 shipped in 3.23.0, SentryMiddleware is an IMiddleware that ASP.NET Core resolves
when a request arrives. Apps that replace or clear the logger providers and run without Sentry's
tracing middleware started the SDK on the first request, so anything before it was lost.

UseSentry now resolves Func<IHub> while ASP.NET Core builds the pipeline, so the SDK starts in
StartAsync again. A missing or invalid DSN now fails host start instead of every request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 75.23%. Comparing base (e6e39fd) to head (de0e155).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5721      +/-   ##
==========================================
+ Coverage   75.21%   75.23%   +0.01%     
==========================================
  Files         516      516              
  Lines       19022    19023       +1     
  Branches     3698     3698              
==========================================
+ Hits        14308    14312       +4     
+ Misses       3858     3857       -1     
+ Partials      856      854       -2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ric-oliv
ric-oliv marked this pull request as ready for review October 13, 2026 14:14
@github-actions github-actions Bot added the risk: medium PR risk score: medium label Oct 13, 2026

@jamescrosswell jamescrosswell left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@jamescrosswell
jamescrosswell merged commit b8b2907 into main Oct 13, 2026
@jamescrosswell
jamescrosswell deleted the fix/aspnetcore-init-on-start branch October 13, 2026 22:29
ric-oliv added a commit that referenced this pull request Oct 14, 2026
…down

AddSentry<TOptions>() starts the SDK when something first resolves the hub. With
the logging providers replaced or cleared (Serilog, ClearProviders()), that can
be much later, and nothing before it is captured. ASP.NET Core had the same
problem (#5721).

SentryHostedService resolves Func<IHub> in its constructor. The host resolves all
hosted services before it starts any, so the SDK is running before the first
StartAsync, whatever the registration order and also with
ServicesStartConcurrently. It closes the SDK on ApplicationStopped, after every
hosted service has stopped, as ASP.NET Core does. TryAddEnumerable keeps one
instance when UseSentry is called twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ric-oliv added a commit that referenced this pull request Oct 16, 2026
…down

AddSentry<TOptions>() starts the SDK when something first resolves the hub. With
the logging providers replaced or cleared (Serilog, ClearProviders()), that can
be much later, and nothing before it is captured. ASP.NET Core had the same
problem (#5721).

SentryHostedService resolves Func<IHub> in its constructor. The host resolves all
hosted services before it starts any, so the SDK is running before the first
StartAsync, whatever the registration order and also with
ServicesStartConcurrently. It closes the SDK on ApplicationStopped, after every
hosted service has stopped, as ASP.NET Core does. TryAddEnumerable keeps one
instance when UseSentry is called twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ric-oliv added a commit that referenced this pull request Oct 16, 2026
…down

AddSentry<TOptions>() starts the SDK when something first resolves the hub. With
the logging providers replaced or cleared (Serilog, ClearProviders()), that can
be much later, and nothing before it is captured. ASP.NET Core had the same
problem (#5721).

SentryHostedService resolves Func<IHub> in its constructor. The host resolves all
hosted services before it starts any, so the SDK is running before the first
StartAsync, whatever the registration order and also with
ServicesStartConcurrently. It closes the SDK on ApplicationStopped, after every
hosted service has stopped, as ASP.NET Core does. TryAddEnumerable keeps one
instance when UseSentry is called twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ric-oliv added a commit that referenced this pull request Oct 16, 2026
…down

AddSentry<TOptions>() starts the SDK when something first resolves the hub. With
the logging providers replaced or cleared (Serilog, ClearProviders()), that can
be much later, and nothing before it is captured. ASP.NET Core had the same
problem (#5721).

SentryHostedService resolves Func<IHub> in its constructor. The host resolves all
hosted services before it starts any, so the SDK is running before the first
StartAsync, whatever the registration order and also with
ServicesStartConcurrently. It closes the SDK on ApplicationStopped, after every
hosted service has stopped, as ASP.NET Core does. TryAddEnumerable keeps one
instance when UseSentry is called twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jamescrosswell pushed a commit that referenced this pull request Oct 19, 2026
…pps (#5739)

* feat(hosting): add an empty Sentry.Extensions.Hosting package

The generic-host UseSentry (#5572) needs Microsoft.Extensions.Hosting.Abstractions
for IHostedService, the host environment and the host builder types. It gets its
own package instead of a new dependency in Sentry.Extensions.Logging, like
Serilog.Extensions.Hosting and NLog.Extensions.Hosting.

SentryGenericHostOptions is the options type for this integration. SentryHostOptions
stays abstract; the subclass exposes EnableLogs and reports the SDK as
sentry.dotnet.extensions.hosting. Sentry and Sentry.Extensions.Logging grant the
package InternalsVisibleTo, as they do for the other integrations, for the shared
options setup and hub registration.

On netstandard2.0 the package uses Hosting.Abstractions 3.1.0 rather than the 2.1.0
floor of Sentry.Extensions.Logging. HostBuilderContext.HostingEnvironment changed
type in 3.0, from IHostingEnvironment to IHostEnvironment, so a build against 2.1.0
that reads it throws MissingMethodException on any 3.0+ host. 3.1.0 also brings
IHostApplicationLifetime to netstandard2.0. Hosting 2.x is out of support.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ref(logging): compile SentryHostOptionsSetup for netstandard2.0

Its only caller so far, Blazor WebAssembly, targets .NET 8+, so it was only
compiled for .NET 6+. The generic host's IHostBuilder overload also runs on
.NET Framework through netstandard2.0. The body already builds there, and
binding through BindableSentryHostOptions behaves the same on every target
(checked on net48).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(hosting): register Sentry.Extensions.Hosting with craft

The registry target needs the entry to add the package to the release registry
on its first stable release, and sdkName makes craft create the
sdks/sentry.dotnet.extensions.hosting entry that the docs and the outdated-SDK
check look up. GenerateSentrySdkNamespaces reads the same lines, so the logging
integrations now treat Sentry.Extensions.Hosting as SDK code and drop its own log
messages.

mainDocsUrl points at the .NET platform page until the generic-host guide exists
(NET-857). The registry target skips prereleases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* build: add Sentry.Extensions.Hosting to the solution and filters

Without it, CI never builds, tests or packs the package. The filters are
regenerated with scripts/generate-solution-filters.ps1; each gains only this
project.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: list Sentry.Extensions.Hosting in the README and bug report form

The documentation link points to the .NET platform page, the same URL as
the package's .craft.yml entry, until the package has its own page
(NET-857).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(hosting): add UseSentry for IHostApplicationBuilder and IHostBuilder

Generic-host apps lost their way to initialize Sentry when the logging
integration stopped doing it (#5595). UseSentry reads the Sentry section and
Logging:Sentry, runs the options callback, then maps the host environment, so an
explicit Environment or SENTRY_ENVIRONMENT still wins. It registers the logger
providers, so Logging.AddSentry() is not needed, and the hub, ISentryClient and
HttpClientFactory instrumentation through AddSentry<SentryGenericHostOptions>.

The IHostApplicationBuilder overloads are not generic: with a TBuilder overload,
builder.UseSentry(o => ...) on a WebApplicationBuilder is ambiguous with
Sentry.AspNetCore's whenever both packages are referenced. The IHostBuilder
overloads go through ConfigureServices and AddLogging, because ConfigureLogging is
not in Hosting.Abstractions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(hosting): start Sentry when the host starts and close it on shutdown

AddSentry<TOptions>() starts the SDK when something first resolves the hub. With
the logging providers replaced or cleared (Serilog, ClearProviders()), that can
be much later, and nothing before it is captured. ASP.NET Core had the same
problem (#5721).

SentryHostedService resolves Func<IHub> in its constructor. The host resolves all
hosted services before it starts any, so the SDK is running before the first
StartAsync, whatever the registration order and also with
ServicesStartConcurrently. It closes the SDK on ApplicationStopped, after every
hosted service has stopped, as ASP.NET Core does. TryAddEnumerable keeps one
instance when UseSentry is called twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(hosting): step aside when Sentry.AspNetCore's UseSentry is also used

A web app can reach the generic UseSentry through a helper constrained to
IHostApplicationBuilder, such as Aspire's ServiceDefaults, while also calling
UseSentry from Sentry.AspNetCore. Both then registered logger providers, so every
logged error was sent twice, and when the generic call came last the SDK started
with its options instead of ASP.NET Core's.

The generic call now does nothing if ASP.NET Core's integration is already
registered. If ASP.NET Core's comes later, the generic logger providers are
disabled and log a diagnostic warning, and ASP.NET Core's registration replaces the
SDK accessor, so the SDK starts with ASP.NET Core's options. Logging.AddSentry()
steps aside the same way (#5694).

To recognize the integration without depending on ASP.NET Core, Sentry.AspNetCore
registers an internal HostIntegrationMarker from Sentry.Extensions.Logging next to
HostLoggerProvidersMarker, and the generic call checks for that service type.
Google Cloud Functions registers the ASP.NET Core logger providers too, so it
registers the marker as well.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(hosting): step aside when Sentry.Maui's UseSentry is also used

MauiAppBuilder implements IHostApplicationBuilder since MAUI 10, and the
Aspire MAUI service defaults template has an AddServiceDefaults<TBuilder>
helper constrained to it, so a MAUI app can reach the generic UseSentry
while also calling UseSentry from Sentry.Maui. When Sentry.Maui's call came
first, the generic one started the SDK again with its own options, and the
app crashed when the DSN had only been set in the Sentry.Maui call.

Sentry.Maui now registers the same marker as Sentry.AspNetCore, so the
generic call steps aside for it too. When the generic call comes first, its
logger providers are disabled, but its SDK accessor still starts the SDK;
the next commit fixes that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(hosting): let the host integration own the SDK when the generic UseSentry comes first

Sentry.Maui starts the SDK itself while MauiApp.Build() runs, and registers
a hub accessor that doesn't start it. AddSentry only replaced an earlier
accessor when the new one started the SDK, so when the generic UseSentry
was called first, its accessor stayed. The first IHub resolution then
started the SDK with the generic options: the app crashed when the DSN was
only set in Sentry.Maui's call, and otherwise sent events with the generic
SDK name and options.

SentryOptions in DI had the same problem in MAUI and ASP.NET Core apps,
because it was registered with TryAdd. ASP.NET Core's blocking-call
detection resolves it, so its stack traces were built from the generic
options.

AddSentry now replaces both, so the integration registered last owns them.
The generic UseSentry returns early when a host integration is already
registered, so in either order that is the host integration.

An app that registers its own SentryOptions or, with Sentry.Maui, its own
Func<IHub> before UseSentry now gets the integration's; the SDK never
started from those registrations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(hosting): register the generic UseSentry only once when it's called twice

Calling UseSentry twice, for example in Aspire's AddServiceDefaults and
again in Program.cs, registered the logger providers twice, so every
logged error was sent as two events and every log twice.

The first call now registers the integration and each call adds only its
options callback, so options from both calls still apply, later ones
winning. The host environment is applied in a PostConfigure, after all
the callbacks, so AdjustStandardEnvironmentNameCasing set by a later call
or a later services.Configure is honored too; before, the first call had
already set the environment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(hosting): add the Sentry.Extensions.Hosting test project

The package had no tests and no API snapshot, so a change to its public
API would go unnoticed. The project targets the same .NET versions as the
package, plus net48 on Windows with Microsoft.Extensions.Hosting 3.1.0,
the package's netstandard2.0 floor. The net48 snapshot can only be
generated on Windows, so CI's verify-api job adds it.

Sentry and Sentry.Extensions.Hosting expose their internals to the
project for the behavior tests that follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: cover Sentry.Extensions.Hosting in the SDK namespaces test

The logging integrations recognize the SDK's own log categories through
SentrySdkNamespaces, which is generated from the package list in
.craft.yml, so that entry is what keeps this package's own log messages
out of Sentry. The new case fails if the entry is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* build: add the hosting tests to the solution and filters

Without it, CI doesn't build or run them. The filters are regenerated
with scripts/generate-solution-filters.ps1; each gains only this project.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(hosting): cover UseSentry and the hosted service on both builders

Each behavior is tested through IHostBuilder and, on .NET 8 and later,
IHostApplicationBuilder: what every overload registers, including IHub and
ISentryClient in DI; binding from the Sentry and Logging:Sentry sections;
the host environment and its casing flag; calling UseSentry twice;
Logging.AddSentry before and after UseSentry; the SDK name on captured
events; and an empty Dsn read from JSON (#3875). The hosted service tests
show the SDK running before the app's own hosted services start with the
logger providers cleared, also when they start concurrently, and an error
logged while the app stops still captured before Close.

The tests log under an app category: logs from Sentry.Extensions.Hosting
are the SDK's own and never reach Sentry. They use Sentry.Testing's
FakeSettings, so SENTRY_DSN or SENTRY_ENVIRONMENT in the shell doesn't
change the results. Sentry.Extensions.Logging and Sentry.Testing expose
their internals to the project.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(aspnetcore): cover the generic UseSentry in web apps

With both UseSentry calls, in either order, one logged error gives one
event with the ASP.NET Core SDK name, and SentryOptions in DI is the
ASP.NET Core options. The generic call goes through a helper constrained
to IHostApplicationBuilder, as Aspire's AddServiceDefaults does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(maui): cover the generic UseSentry next to Sentry.Maui's

With both calls, in either order, one logged error gives one event with
the MAUI SDK name and SentryOptions in DI is the MAUI options. The DSN is
only set in Sentry.Maui's call, so if the generic options were used, the
generic-first case would fail to start the SDK.

The tests run in a collection with parallelization off, as in the hosting
and ASP.NET Core test projects. Sentry.Maui goes through the global hub, so
another test class starting or closing the SDK at the same time swapped it
underneath them: on the iOS simulator one run saw no event and another an
extra one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(samples): initialize Sentry with UseSentry in the generic host sample

The sample called SentrySdk.Init by hand and then added the logging
integration, so its options lived in code only and the host environment
was ignored. It now calls UseSentry, which reads the Sentry section of
appsettings.json, uses the host environment and closes the SDK on
shutdown. SendDefaultPii moves to that section. EnableLogs is turned on
there too: logs are opt-in with the host integrations' options, so
without it the sample would stop sending the structured logs it
configures. SampleHostedService still gets IHub from DI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(samples): use UseSentry in the Azure Functions sample

The sample initialized the SDK with SentrySdk.Init before building the
host and added the logging integration separately. It now calls the
IHostBuilder overload of UseSentry on its HostBuilder, which also adds
the logger providers and closes the SDK when the host shuts down.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(hosting): warn when a web app uses only the generic UseSentry

A web app reaches the generic UseSentry through a helper constrained to
IHostApplicationBuilder, such as Aspire's AddServiceDefaults, or through
builder.Host. Sentry then works, but without the ASP.NET Core integration:
events have no request data and requests aren't traced, and nothing says so.

When UseSentry runs on a WebApplicationBuilder or its Host, and the ASP.NET
Core integration isn't registered by the time the host starts, the hosted
service logs one warning through the host logger. It names UseSentry from
Sentry.AspNetCore and shows the builder-type branch for shared helpers. The
check reads the builder's type name, so the package still doesn't depend on
ASP.NET Core.

The branch calls SentryWebApplicationBuilderExtensions.UseSentry(web) as a
static method. Aspire's ServiceDefaults file is declared in namespace
Microsoft.Extensions.Hosting, this package's namespace, and C# looks for
extension methods there before it looks at using directives, so
web.UseSentry() in that file would bind to the generic overload again. A
test runs the snippet from a helper declared in that namespace.

An earlier version keyed off ASP.NET Core's GenericWebHostService being
registered. Azure Functions apps with the ASP.NET Core integration register
that service too, and for them the generic UseSentry is the right call, so
they'd have been warned on every start. Their builders are HostBuilder and
FunctionsApplicationBuilder, which the builder-type check never matches. The
cost is that a plain HostBuilder with ConfigureWebHostDefaults isn't
detected.

The warning's category is filtered from Sentry structured logs, so it isn't
sent to Sentry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(hosting): warn when a MAUI app uses only the generic UseSentry

MauiAppBuilder implements IHostApplicationBuilder since MAUI 10, so a helper
constrained to it, such as the Aspire MAUI ServiceDefaults, reaches the generic
UseSentry. Sentry then works, but it starts only when the app first uses a
logger or IHub, and the MAUI integration's navigation and UI breadcrumbs are
missing.

MAUI never runs hosted services, so the web app warning can't be used here.
When UseSentry runs on a MauiAppBuilder and Sentry.Maui's integration isn't
registered, the logger provider writes one warning to standard error when
it's created, which is also when the SDK starts. That's the channel
UninitializedSdkWarning already uses for setup mistakes, and it doesn't need
Debug to be on: on the Android emulator it shows in logcat under DOTNET, and
on the iOS simulator in the app's system log. A packaged Windows app has no
console, so it doesn't show there. The warning names UseSentry from
Sentry.Maui and shows the builder-type branch for shared helpers.

As for web apps, the branch calls
SentryMauiAppBuilderExtensions.UseSentry(maui) as a static method, because
maui.UseSentry() in a file declared in namespace
Microsoft.Extensions.Hosting binds to the generic overload. A test runs the
snippet from a helper declared in that namespace.

The builder type check now returns an internal enum for web, MAUI or other
apps, so the shared registration still takes one parameter.

SentryHostedService is registered in MAUI apps too, where nothing registers
IHostApplicationLifetime. It now resolves the lifetime with GetService, so
code that enumerates the hosted services, such as a library that runs them
in MAUI, no longer fails to resolve it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(mel): name the packages that initialize Sentry in the v7 init error

Logging.AddSentry() no longer initializes the SDK (#5595). An upgraded
app learns that from one message: at startup for a DSN under
Logging:Sentry, or at compile time for AddSentry(dsn), Dsn and
InitializeSdk. It pointed to SentrySdk.Init or "UseSentry via one of the
integrations", and a worker service can't get from there to
Sentry.Extensions.Hosting. In a dogfooding run, an agent upgrading a v6
worker found the package only by listing the feed it installed from.

The message now names UseSentry from Sentry.Extensions.Hosting,
Sentry.AspNetCore and Sentry.Maui, and says UseSentry reads the removed
settings from the Sentry section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(hosting): cover a disabled SDK and starting hosted services in MAUI

Codecov reported two branches in the new package that no test reached:

- The redundant generic UseSentry warns through the hub's options, which
  a disabled SDK ("Dsn": "", supported since #3875) doesn't have. The
  new test runs the generic UseSentry, then Sentry.AspNetCore's with an
  empty DSN, and starts the app. Only this order reaches that code: with
  ASP.NET Core's call first, the generic one returns early.
- SentryHostedService gets IHostApplicationLifetime with GetService,
  because MAUI doesn't register it. The MAUI test resolved the hosted
  services but never started them, so StartAsync with no lifetime was
  untested. It now starts them.

Both tests fail when the null check they cover is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This was referenced Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk: medium PR risk score: medium

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants