Repository navigation
Injecting scoped/request services into Ocelot DelegatingHandler #2426
|
My ocelot DelegatingHandler registered via QuestionWhat is the recommended pattern for dependencies in Ocelot Specifically:
Why this mattersThe 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 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
Thanks for clarifying the supported dependency/lifetime model. |
Replies: 7 comments 2 replies
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 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
I'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 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 |
Consider any delegating handler as a transient service. My opinion is that all handlers should be free of any state or dependencies.
Nope! You are mixing concerns. Such a design violates SOLID principles. Keeping or using request-scoped data in a delegating handler is a bad design. All of these (claims, user identity, request context), as authentication artifacts, must be processed inside both Ocelot's AuthenticationMiddleware and AuthorizationMiddleware.
We only have a Delegating Handlers chapter in the docs, where we explain Ocelot's own handlers and how custom handlers are processed (their order). We haven't published any best practices on designing custom handlers, because we strongly believe that experienced developers know how to design handlers and consume different services inside them if applicable.
No, it doesn't. |
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
Registered delegating handlers are utilized by Requester's I believe that nothing is restricted in Ocelot. It is a question of design, registration in DI, and utilization by
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. |
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? 😅 |
|
@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 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 MessageInvokerPool in 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 affect MessageInvokerPool registration, and/or MessageInvokerPool's registration is a limit.
You showed the location of this cache. It is located inside the
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.
"Per-request behavior" means scoped behavior. OK. 1. Change the registration of
|
|
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. |
|
Hey @raman-m thank you again for your responses you pointed out valuable information as the fact of using the auth middleware instead playing directly with delegatingHandler, i also will explore more the IRequestScopedDataRepository, i initially assumed that Ocelot was registering DelegatingHandlers as transient because of some Ocelot-specific internal design. I now realize that using a transient lifetime for DelegatingHandlers is actually consistent with Microsoft's guidance.
Yeah my statement was too broad, this is more a behavior in ocelot since seems it resolves dependencies from root provider, this is the exact exception System.InvalidOperationException: 'Cannot resolve 'System.Collections.Generic.IEnumerable`1[System.Net.Http.DelegatingHandler]' from root provider because it requires scoped service 'My service'.'
Not sure if we can state that categorically, Microsoft's documentation explicitly describes message handlers as a good fit for reading or modifying request headers: The current ASP.NET Core documentation also discusses the "surprising behavior when a handler consumes a scoped service" and provides three approaches for safely sharing per-request state with message handlers:
Yeah this is consistent with what i experienced and tried to point out earlier regarding the "cache" behavior, in my scenario i created MyService to encapsulate the logic for interacting with HTTP headers so that the DelegatingHandler itself wouldn't become polluted with that logic, i made my MyService depends on IHttpContextAccessor, imagine the method MyService.ProcessRequestHeaders() and for sake of the example, let's say that it will print the headers on console, now i have
public class MyService
{
public MyService(IHttpContextAccesor httpContextAccessor)
{
InitializePropertiesFromHttpContext(httpContextAccessor);
}
}
I'm not saying that Ocelot's design is necessarily wrong. If I know that the data I'm dealing with is request-specific, I should also question myself why I'm putting it into a transient service that I expect to behave per request rather than per resolution. That said, the combination of registering DelegatingHandlers as transient while resolving them from the root provider and then retaining the resulting instances in the cached MessageInvoker feels like a somewhat non-obvious behavior from a DI/lifetime perspective, probaly worthy to mention that in the delegatingHandler document? maybe a warning? "Note that although DelegatingHandlers are registered as transient, Ocelot resolves them from the root provider — meaning scoped dependencies will fail at resolution time. Additionally, for performance reasons, resolved handler instances are cached inside a singleton (MessageInvokerPool), so any captured dependency effectively becomes singleton-scoped for the lifetime of that route, request-specific data should instead be obtained through an appropriate per-request mechanism." |
Consider any delegating handler as a transient service. My opinion is that all handlers should be free of any state or dependencies.
In practice, in Ocelot, a constructed delegating handler for a route is a singleton being "cached" in
MessageInvokerPoolfor performance reasons. This singleton behavior is not a problem because current Ocelot handlers don't inject any services either via the constructor or on the fly from the service provider. If a developer injects any stateful custom handlers into the Ocelot pipeline, they will be a bit surprised. For more details, read below where e…