C
C#3y ago
camel

Inject http client only for specified service [Answered]

I have a RemoteApiClient that I want to inject to the FooBarService and only to the FooBarService. The reason for this is that the RemoteApiClient is not really meant to be used directly. How do I achieve this? Additionally, the IMemoryCache is injected into the FooBarService, but the IMemoryCache is also used elsewhere.
builder.Services.AddMemoryCache();
builder.Services.AddHttpClient<RemoteApiClient>()
.AddTransientHttpErrorPolicy(policyBuilder => policyBuilder.WaitAndRetryAsync(Backoff.DecorrelatedJitterBackoffV2(TimeSpan.FromSeconds(1), 5)));

builder.Services.AddScoped<FooBarService>();
builder.Services.AddMemoryCache();
builder.Services.AddHttpClient<RemoteApiClient>()
.AddTransientHttpErrorPolicy(policyBuilder => policyBuilder.WaitAndRetryAsync(Backoff.DecorrelatedJitterBackoffV2(TimeSpan.FromSeconds(1), 5)));

builder.Services.AddScoped<FooBarService>();
9 Replies
pip
pip3y ago
Have FooBarService as a param in your RemoteApiClient constructor? or am I missing something
camel
camelOP3y ago
The RemoteApiClient is a dependency of FooBarService. FooBarService must use the RemoteApiClient internally.
Becquerel
Becquerel3y ago
you can't restrict which services your registered dependencies can be injected to, outside of not requesting them in the constructors of other services kind of goes against the spirit of DI
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
camel
camelOP3y ago
Alright thank you guys for the answers. I’ll see if I’ll go the way with the second service collection or if I’ll just not bother changing it.
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
camel
camelOP3y ago
It's definitely not what I want 😄 two service collections sounds like an antipattern
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Accord
Accord3y ago
✅ This post has been marked as answered!
Want results from more Discord servers?
Add your server