Skip to content

Guidance needed: injecting scoped/request services into Ocelot DelegatingHandler #2425

Closed

Description

@yerald-mora

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:

  1. Are constructor dependencies expected to be singleton/transient-only?
  2. For request-scoped data (claims, user identity, request context), should handlers resolve services inside SendAsync from HttpContext.RequestServices maybe or from a new scope created using IServiceScopeFactory?
  3. Is there an official extension point preferred over DelegatingHandler for scoped/request-bound logic?
  4. 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 👇

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

  1. raman-m commented on Sep 21, 2026

    @raman-m
    Member

    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.

    Wow!

    I want to follow the intended Ocelot design for safe per-request behavior.

    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?

  2. yerald-mora commented on Sep 21, 2026

    @yerald-mora
    Author

    Is this code research to reveal a potential bug in Ocelot, or is it a long question?

    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 DelegatingHandler registered 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 the DelegatingHandler, is actually a bug, how i said

    I’m not fully sure how that "cache" behaves internally.

    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 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?

    And what's your LinkedIn

    Yerald Mora 😉

  3. raman-m commented on Sep 24, 2026

    @raman-m
    Member

    Hello Yerald❕

    So yeah, basically, it's a long question xD. I just tried to provide all the necessary context.

    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?

    I'm not sure whether the "caching" of the HttpMessageInvoker, which ultimately triggers the execution of the DelegatingHandler, is actually a bug, how i said

    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...

  4. raman-m commented on Sep 24, 2026

    @raman-m
    Member

    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 DelegatingHandler.

    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 OcelotBuilder for 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.

    In Ocelot, are handlers intentionally registered in a way that prevents them from using scoped dependencies?

    Registered delegating handlers are utilized by Requester's MessageInvokerPool class:

    List<DelegatingHandler> handlers = _handlerFactory.Get(route);

    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?

    Should we avoid using request-bound logic inside a DelegatingHandler?

    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.

  5. raman-m commented on Sep 24, 2026

    @raman-m
    Member

    @yerald-mora opened on Sep 19

    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

    since DelegatingHandler are transient so can't depend on scoped services

    Incorrect. In theory, any transient service is able to utilize any scoped service without problems due to its transient nature. But not vice versa.

    scoped service MyService, and runtime throws

    Report log data. Show the exception being generated!

    System.InvalidOperationException: Cannot resolve scoped service 'MyService' from root provider.
    

    Is this the error we are talking about? 😅
    OR 👇

    System.InvalidOperationException : Cannot consume scoped service 'MyService' from singleton 'AnotherService'.
    
  6. raman-m commented on Sep 24, 2026

    @raman-m
    Member

    @yerald-mora opened on Sep 19

    The DI error can be avoided by changing scoped dependency lifetimes, but that appears risky since Ocelot seems to cache handler/invoker instances:

    return _handlersPool.GetOrAdd(
    new MessageInvokerCacheKey(downstreamRoute),
    cacheKey => new Lazy<HttpMessageInvoker>(() => CreateMessageInvoker(cacheKey.Route))
    ).Value;

    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:

    services.AddSingleton<IMessageInvokerPool, MessageInvokerPool>();

    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.

    I’m not fully sure how that "cache" behaves internally,

    You showed the location of this cache. It is located inside the MessageInvokerPool singleton service. If you register MessageInvokerPool as 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:

    private readonly ConcurrentDictionary<MessageInvokerCacheKey, Lazy<HttpMessageInvoker>> _handlersPool;

    but it could potentially retain my dependency instance, causing stale request data or cross-request leakage.

    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?

    I want to follow the intended Ocelot design for safe per-request behavior.

    "Per-request behavior" means scoped behavior. OK.

    1. Change the registration of MessageInvokerPool to 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:

    public virtual HttpMessageInvoker Get(DownstreamRoute downstreamRoute)
    {
    // Since the comparison is based on the downstream route object reference,
    // and the QoS Options properties can't be changed after the route is created,
    // we don't need to use the timeout value as part of the cache key.
    return _handlersPool.GetOrAdd(
    new MessageInvokerCacheKey(downstreamRoute),
    cacheKey => new Lazy<HttpMessageInvoker>(() => CreateMessageInvoker(cacheKey.Route))
    ).Value;
    }

    to

        public class MyMessageInvokerPool : MessageInvokerPool
        {
            public MyMessageInvokerPool(IDelegatingHandlerFactory handlerFactory, IOcelotLoggerFactory loggerFactory)
                : base(handlerFactory, loggerFactory) { }
        
            public override HttpMessageInvoker Get(DownstreamRoute downstreamRoute)
            {
                return CreateMessageInvoker(downstreamRoute);
            }
        }

    Finally, inject the new behavior and register it as a scoped service however you want:

        services.RemoveAll<IMessageInvokerPool>();
        services.AddScoped<IMessageInvokerPool, MyMessageInvokerPool>();

    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.

  7. added
    question
    Delegating Handlers
    Dependency Injection
    on Sep 24, 2026
  8. raman-m commented on Sep 28, 2026

    @raman-m
    Member

    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?

  9. locked and limited conversation to collaborators on Sep 28, 2026
  10. converted this issue into a discussion #2426 on Sep 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Delegating HandlersDependency Injectionquestion

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions