.NET: how to consume a scoped service from a singleton?
This is a short post about a very specific C#/.NET topic. They say one needs to pick their battles. Here I decided to pick a battle with a StackOverflow answer from 2018 and a couple of fellow tech bloggers, because I have opinions. This is not exactly a tutorial, so I assume the reader has some basic understanding of .NET, its DI mechanisms and service lifetimes. Q: In .NET, how to consume a…
A common challenge in .NET programming is consuming a scoped service from a singleton. Microsoft's documentation discourages the usage of the Service Locator pattern. The typical solution involves creating a scope on demand using IServiceScopeFactory. However, this approach still carries the disadvantages of the Service Locator pattern.
To address this issue, the author proposes creating a thin wrapper, MyWrappedScoped, that allows scoped services to act like singletons. MyWrappedScoped takes an IServiceScopeFactory in its constructor and provides a Forward method to seamlessly call scoped service methods as if they were singleton methods. This approach avoids the pitfalls of the Service Locator pattern while maintaining the desired functionality.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.