Start Debugging

dependency-injection

16 posts · Page 1 of 2

How does Microsoft.Extensions.DependencyInjection resolve a service internally, from AddSingleton to the instance?

AddSingleton only appends a ServiceDescriptor to a list. BuildServiceProvider indexes those descriptors, and the first GetService builds a call-site tree with reflection, caches it, and wraps it in an accessor delegate. Singletons are stored on the call site itself, scoped instances in a per-scope dictionary, and after the second resolve of a non-singleton the container compiles an IL DynamicMethod on the thread pool. Walked through the .NET 11 source and observed with reflection, EventSource events and BenchmarkDotNet.

How to initialize interdependent async singletons at startup in ASP.NET Core

Give each singleton a memoized InitializeAsync that awaits its own dependencies, then await them all from IHostedLifecycleService.StartingAsync. Registration order stops mattering, Kestrel does not accept requests until init finishes, and a failure stops the host. Compared against init before app.Run, IHostedService.StartAsync, and a BackgroundService with a readiness check on ASP.NET Core 10.0.10.
Next