Blog Logo
TAGS

Dangers & Gotchas of Scoped Services in OptionsBuilder

In this blog post, Andrew Lock discusses the dangers and gotchas of using scoped services with the IOptions pattern. He provides a brief overview of strongly-typed configuration in ASP.NET Core and the difference between IOptions<> and IOptionsSnapshot<>. He then describes how to inject services when building strongly-typed settings using the OptionsBuilder<> API, and looks at what can happen if you try to use Scoped services with OptionsBuilder<>. Lock advises readers to create a new scope using IServiceProvider.CreateScope() if they need to use Scoped services inside OptionsBuilder<T>.Configure<TDeps>(). He also states that readers should be aware that the service lives in its own scope, separate from the main scope associated with the request. Lock concludes with a tl;dr stating that readers should create a new scope to resolve the service directly if they need to use Scoped services inside OptionsBuilder<T>.Configure<TDeps>().