📎 Webclip
The dangers and gotchas of using scoped services in IConfigureOptions
The post explains how strongly typed settings are configured in ASP.NET Core, including the order in which configuration steps run and the difference between IOptions<> and IOptionsSnapshot<>. It also shows how IConfigureOptions<> can be used to build options from other services.
Reading notes#
- ASP.NET Core binds configuration values to a POCO through the Options pattern, and configuration steps run in sequence.
IOptions<>exposes settings throughValueand has Singleton lifetime.IOptionsSnapshot<>supports named options, configuration reloads, and has Scoped lifetime.IConfigureOptions<>lets options depend on other registered services.- If a Singleton option depends on a Scoped service through
IConfigureOptions<>, ASP.NET Core raises a captive dependency error in Development. - One workaround is to use
IOptionsSnapshot<>together with a ScopedIConfigureOptions<>, so options are rebuilt per request. - The safer general approach is to inject
IServiceProviderintoIConfigureOptions<>, create a new scope withCreateScope(), and resolve the Scoped service from that scope. - The scope created inside
IConfigureOptions<>is different from the request scope, so the same Scoped service may have different instances within one request.
