Repository navigation
Description
My ocelot DelegatingHandler registered via builder.Services.AddOcelot() .AddDelegatingHandler<RequestHandler>(); depends on a scoped service MyService, and runtime throws, which after reading the docs would be kind of expected since DelegatingHandler are transient so can't depend on scoped services https://ocelot.readthedocs.io/en/develop/features/delegatinghandlers.html
Question
What is the recommended pattern for dependencies in Ocelot DelegatingHandler?
Specifically:
- Are constructor dependencies expected to be singleton/transient-only?
- For request-scoped data (claims, user identity, request context), should handlers resolve services inside
SendAsyncfromHttpContext.RequestServicesmaybe or from a new scope created usingIServiceScopeFactory? - Is there an official extension point preferred over
DelegatingHandlerfor scoped/request-bound logic? - Does Ocelot support creating custom DelegatingHandler instances per request (using request scope), or are handlers intentionally created from root/cached and therefore expected to avoid scoped constructor dependencies?
Why this matters
The DI error can be avoided by changing scoped dependency lifetimes, but that appears risky since Ocelot seems to cache handler/invoker instances 👇
Ocelot/src/Requester/MessageInvokerPool.cs
Lines 31 to 34 in 11989f8
| return _handlersPool.GetOrAdd( | |
| new MessageInvokerCacheKey(downstreamRoute), | |
| cacheKey => new Lazy<HttpMessageInvoker>(() => CreateMessageInvoker(cacheKey.Route)) | |
| ).Value; |
I’m not fully sure how that "cache" behaves internally, but it could potentially retain my dependency instance, causing stale request data or cross-request leakage.
I want to follow the intended Ocelot design for safe per-request behavior.
Environment
- Ocelot: 24.0.0
- .NET: 9
Thanks for clarifying the supported dependency/lifetime model.
Activity
raman-m commentedon Sep 21, 2026
Wow!
Very interesting enquiry...
Is this code research to reveal a potential bug in Ocelot, or is it a long question, Mr. @yerald-mora?
And what's your LinkedIn?
yerald-mora commentedon Sep 21, 2026
Hi @raman-m, thank you for taking the time to review my question 😊. The code research is more about figuring out how to properly use the tool for my particular need: providing a scoped service inside a
DelegatingHandlerregistered by Ocelot.So yeah, basically, it's a long question xD. I just tried to provide all the necessary context.
I'm not sure whether the "caching" of the
HttpMessageInvoker, which ultimately triggers the execution of theDelegatingHandler, is actually a bug, how i saidI'm also not sure what the intended design is, so I just want to confirm whether there is an official way to use a scoped service inside a
DelegatingHandler.In Ocelot, are handlers intentionally registered in a way that prevents them from using scoped dependencies? Should we avoid using request-bound logic inside a
DelegatingHandler?Yerald Mora 😉
raman-m commentedon Sep 24, 2026
Hello Yerald❕
OK. For questions we have a dedicated Discussions space, especially the Questions & Answers category. Please copy all your questions from this thread to a new Q&A discussion (I don't wanna convert it to a discussion). And I'll answer. I expect that the new discussion will be a long thread. We will reshare the knowledge with the community, right?
Let's focus on the bug here. What error do you actually see in the log? Could you attach
ocelot.json,Program.cs, and all the code, please?Better yet, just upload the app to your repository as public. And I'll review...
raman-m commentedon Sep 24, 2026
You are asking me about .NET software? Wrong repo. You could go to the Microsoft forums, dotnet repositories, and ask the .NET team how to design a delegating handler. 😉 Just kidding.
Officially, we don't publish any recommendations on designing Delegating Handlers in Ocelot. Instead, there is a dedicated "Delegating Handlers" docs chapter which explains the extended
OcelotBuilderfor adding custom handlers in an Ocelot app. Have you seen the code of these OcelotBuilder helpers, I mean, the AddDelegatingHandler methods? They were designed to act as transient services. But I'm not 100% sure.What I'm confident about now is that Ocelot does not support scoped service injection in the handler constructor. Unfortunately, the Ocelot Builder model is limited when it comes to Delegating Handlers.
Registered delegating handlers are utilized by Requester's
MessageInvokerPoolclass:Ocelot/src/Requester/MessageInvokerPool.cs
Line 42 in fcebf2b
I believe that nothing is restricted in Ocelot. It is a question of design, registration in DI, and utilization by
MessageInvokerPool.You are able to construct a scoped delegating handler. But why do you need to store scoped data or object state? I think that is bad design. I am pretty sure that all delegating handlers must be transient and free of any state or data!
If you have scoped (request) data, then consider developing a custom middleware to inject into Ocelot's pipeline instead of delegating handlers! Finally it depends on the task you solve. What task are you doing in your delegating handler? What scoped data do you store that needs to be shared across all services for a single request?
Yes! In my personal opinion, keeping scoped data in a handler is a bad design. Data must be stored in a custom middleware or in a special scoped service injected into a custom middleware constructor. Moreover, there is a dedicated IRequestScopedDataRepository service from DI that is used in the Ocelot core. Just use it — it's a helpful service. Just a wrapper, but a helpful one.
raman-m commentedon Sep 24, 2026
Incorrect. In theory, any transient service is able to utilize any scoped service without problems due to its transient nature. But not vice versa.
Report log data. Show the exception being generated!
Is this the error we are talking about? 😅
OR 👇
raman-m commentedon Sep 24, 2026
@yerald-mora opened on Sep 19
What's risky? Ocelot actually caches handler instances that behave as singletons, including all attached custom delegating handlers. And this cache is part of
MessageInvokerPool, which is a singleton service injected as a singleton:Ocelot/src/Requester/ServiceCollectionExtensions.cs
Line 10 in fcebf2b
Do you need scoped behavior and don't know how to change singleton registration to a scoped one? Do you need my instructions?
FYI, we register
MessageInvokerPoolin DI and we cache constructed handler instances due to performance reasons. If you construct the final delegating handler on the fly, then performance will degrade. If it's OK with you, then change the singleton registration to scoped. No problem. It is possible. Once again, Ocelot was designed for maximum performance without scoped services in DI which affectMessageInvokerPoolregistration, and/orMessageInvokerPool's registration is a limit.You showed the location of this cache. It is located inside the
MessageInvokerPoolsingleton service. If you registerMessageInvokerPoolas a scoped service, then this cache does not matter. The cache collection will always be empty for each request in the case of scoped registration of the service, because the pool variable is not a static one:Ocelot/src/Requester/MessageInvokerPool.cs
Line 10 in fcebf2b
In theory, yes, but in practice it depends on the type of data you store in a scoped service, I assume, in your scoped delegating handler.
Here is my little story...
"Let's say Yerald designed a delegating handler keeping user A's data in a scoped storage for the 1st request. Ocelot cached this handler and cached user's data implicitly in a singleton handler.
Suppose the 2nd user requested the same route, and the badly registered handler returned the data for the 1st user. Ta-da 🎉"
In that case, why should Ocelot be responsible for data leakage?
Once again, you see a runtime error because you are trying to use a scoped service in a singleton context.
Ocelot was designed with mostly singleton services, and the user is unable to inject scoped services into them, right? Where is the leakage?
"Per-request behavior" means scoped behavior. OK.
1. Change the registration of
MessageInvokerPoolto be a scoped service to "switch off" the delegating handlers' cache inside it.Develop and inject whatever scoped services you want. Please note, that switching off the cache is possible if you override the virtual method from:
Ocelot/src/Requester/MessageInvokerPool.cs
Lines 26 to 35 in fcebf2b
to
Finally, inject the new behavior and register it as a scoped service however you want:
2. Don't change the registration of
MessageInvokerPool— keep its registration as-is (singleton) and utilize the handlers cache.Design and register only singleton services that consume the dedicated IRequestScopedDataRepository service on the fly inside of these "singleton" services.
raman-m commentedon Sep 28, 2026
I think this conversation is over. There's no real offer of improvement or any other suggestions, and I don't see any possible contributions on your part.
@yerald-mora, did you get enough information from my side?