C#C
C#2y ago
49 replies
frobnicate

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:
public class MyService
{
  public MyService(HttpClient httpClient)
  {
    // ....
  }

  public async Task<Whatever> MyEndpoint()
  {
    return await _httpClient //...
  }
}

public class MyConsumer<T> where T : class
{
    public MyConsumer(IServiceProvider serviceProvider)
    {
      // ...
    }

    public async Task<Foobar> PerformMultipleRequests()
    {
      //some loop
      var myService = _serviceProvider.GetRequiredService<T>();
      myService.MyEndpoint()
      // ...
    }
}


† 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
Was this page helpful?