How to avoid the Service Locator anti pattern when needing to instantiate multiple of a DI instance?
I have a Typed Client (Service Agent) as per https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-8.0#typed-clients, and it is consumed in a class as a ctor DI, but I need to instantiate a new instance per request.† So instead I currently use a Service Locator, which is an anti pattern, and thus I'd like to avoid this. I'm not sure how a factory would solve it, since then I'd just move the DI instantiating problem to the factory.
Code example of what I have:
† The reason I need to spawn a client / service per request, is that the endpoint I'm writing against doesn't accept multiple simultaneous requests from the same client. Right now I'm just building around it but hopefully it'll get fixed
22 Replies
Why does the limitation of the external API make it so you need to create a scope?
I can imagine you'd want your MyService to be a Singleton, to manage that there will only be one concurrent request
Because I need multiple requests to run in parrallel, and the external API does not allow multiple concurrent requests from the same client
What do you mean "from the same client"?
is it a HTTP call and identified by a header or user agent?
In practice, when I use the same instance of a HttpClient, to do multiple requests on the API, it will fail.
If I make a HttpClient per request, it works. I'm not sure why
It's a different company that makes the external API and they haven't documented it :catshrug:
just curious, how do you notice it fails? Do you get a certain response?
500
oopsie
I think I'd make MyService a transient/scoped, and it'll get a
IHttpClientFactory
that way, MyConsumer
can rely on MyService
to do the right logic
you want this weird behavior to be in your MyService
such that if it ever changes, you change the single part responsible for itSo MyService has a ctor DI
IHttpClientFactory
?yes
Use the IHttpClientFactory - .NET
Learn how to use the HttpClient and IHttpClientFactory implementations with dependency injection in your .NET workloads.
I had hoped I could do it with typed clients :c
Oh well
I don't really get the point of typed clients, but that might just be me
Not needing to use strings and being able to put more behaviour in the service
But thanks regardless!
How do I mark it as solved?
you can use /close
but feel free to open again or ask another question 😁
Unknown User•11mo ago
Message Not Public
Sign In & Join Server To View
If I make a queue do they run in parallel?
Unknown User•11mo ago
Message Not Public
Sign In & Join Server To View
But if I queue with a single client I have the same issue of not having multiple concurrent requests
Unknown User•11mo ago
Message Not Public
Sign In & Join Server To View
The requests are slow, that's why I want them to be in parallel
Unknown User•11mo ago
Message Not Public
Sign In & Join Server To View
Ok