frobnicate
frobnicate
CC#
Created by frobnicate on 2/2/2024 in #help
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()
// ...
}
}
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
50 replies
CC#
Created by frobnicate on 2/1/2024 in #help
In a Typed Client, do you need to explicitly handle bad response codes?
So I've been refactoring to use Typed Clients, and now I'm wondering about handling bad responses, which they don't seem to do in the example in the docs, so I'm confused if that's handled by the Polly-layer policies you set when registering the Client? Code https://paste.mod.gg/gnmecbwforev/0 Docs https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests#implement-your-typed-client-classes-that-use-the-injected-and-configured-httpclient
3 replies