C
C#4w ago
Dachi

Dependency injection

I have 2 classes, 1 Wolt adapter and second one is Glovo adapter. Both of them need http clients to be injected but the problem is that when i run both of them Wolt's http client is not being injected but when i run onlt Wolt adapter it works. It does not even log anything. could somebody explain why?
35 Replies
Dachi
DachiOP4w ago
https://codeshare.io/anqNPj here is the code when i run both wolt and glovo wolts http client does not even write Log inforamtion or console writeline 2025-09-07 16:07:23 [12:07:23 INF] Starting up the service 2025-09-07 16:07:23 [12:07:23 INF] Using SQLite database for Glovo state at: Data Source=/app/data/glovo_state.db 2025-09-07 16:07:23 [12:07:23 INF] Integration 'Glovo' is ENABLED. Setting up its background service. 2025-09-07 16:07:23 [12:07:23 INF] Integration 'Wolt' is ENABLED. Setting up its background service. 2025-09-07 16:07:23 [12:07:23 INF] [] Successfully configured HttpClient for GLovo Adapter. 2025-09-07 16:07:23 Successfully configured HttpClient for GLovo Adapter.
Jimmacle
Jimmacle4w ago
how do you know it's not being injected? what code are you running that you expect to get a wolt httpclient?
Dachi
DachiOP4w ago
it is here GlovoAdapter and WoltAdaper both have HttpClient in their constructor and i inject them from here @Jimmacle
c#
foreach (var (adapterName, adapterConfig) in integrationsConfig.Adapters)
{
if (!adapterConfig.Enabled)
{
Log.Information("Integration '{AdapterName}' is disabled in configuration.", adapterName);
continue;
}

Log.Information("Integration '{AdapterName}' is ENABLED. Setting up its background service.",
adapterName);

services.AddHostedService(provider =>
{
try
{
IIntegrationAdapter adapter = adapterName.ToUpperInvariant() switch
{
"WOLT" => provider.GetRequiredService<WoltAdapter>(),
"GLOVO" => provider.GetRequiredService<GlovoAdapter>(),
_ => throw new NotSupportedException($"The adapter '{adapterName}' is not supported.")
};

var loggerFactory = provider.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger<ScheduledIntegrationWorker>();
return new ScheduledIntegrationWorker(logger, adapter, adapterConfig);
}
catch (Exception e)
{
Log.Error(e, "Integration '{AdapterName}' is disabled in configuration.", adapterName);
throw;
}
});
}
c#
foreach (var (adapterName, adapterConfig) in integrationsConfig.Adapters)
{
if (!adapterConfig.Enabled)
{
Log.Information("Integration '{AdapterName}' is disabled in configuration.", adapterName);
continue;
}

Log.Information("Integration '{AdapterName}' is ENABLED. Setting up its background service.",
adapterName);

services.AddHostedService(provider =>
{
try
{
IIntegrationAdapter adapter = adapterName.ToUpperInvariant() switch
{
"WOLT" => provider.GetRequiredService<WoltAdapter>(),
"GLOVO" => provider.GetRequiredService<GlovoAdapter>(),
_ => throw new NotSupportedException($"The adapter '{adapterName}' is not supported.")
};

var loggerFactory = provider.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger<ScheduledIntegrationWorker>();
return new ScheduledIntegrationWorker(logger, adapter, adapterConfig);
}
catch (Exception e)
{
Log.Error(e, "Integration '{AdapterName}' is disabled in configuration.", adapterName);
throw;
}
});
}
those adapters are registered from here like it loops thru adapters (glovo, wolt) and checks which one is enabled and registeres them
Jimmacle
Jimmacle4w ago
is WoltAdapter ever actually instantiated then? the logging in your httpclient configuration method will only run when the httpclient is actually created like, does the service work or do you get an error?
Dachi
DachiOP4w ago
what do you mean by actually created?
Jimmacle
Jimmacle4w ago
your httpclient configuration code only runs once you actually get a client from the factory it doesn't run when you configure the services
Dachi
DachiOP4w ago
in the loop i register 2 hosted services one for glovo adapter and second one is for wolt. When i ENABLE both of them Wolt does not start up, glovo works fine. But when i enable only wolt, it works
Jimmacle
Jimmacle4w ago
how are you injecting the httpclient into each service?
Dachi
DachiOP4w ago
c#
services.AddHttpClient<WoltAdapter>("WoltClient", (serviceProvider, client) =>
{
try
{
Log.Information("Start configured HttpClient for Wolt Adapter.");
Console.WriteLine("Start configured HttpClient for Wolt Adapter.");
var config = serviceProvider.GetRequiredService<IntegrationsConfig>();
var woltAdapterCredentials = config.Adapters["Wolt"].Credentials;
var woltUri = new Uri(hostContext.Configuration["WoltApi:BaseUrl"] ??
throw new InvalidOperationException("WoltUrl not found"));

client.BaseAddress = woltUri;
var byteArray =
Encoding.ASCII.GetBytes($"{woltAdapterCredentials.Username}:{woltAdapterCredentials.Password}");
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
Log.Information("END Successfully configured HttpClient for Wolt Adapter.");
Console.WriteLine("END Successfully configured HttpClient for Wolt Adapter.");
}
catch (Exception e)
{
Log.Error(e, "Failed wolt httpclient");
throw;
}
})
.AddPolicyHandler(GetRetryPolicy())
.AddPolicyHandler(GetCircuitBreakerPolicy());
c#
services.AddHttpClient<WoltAdapter>("WoltClient", (serviceProvider, client) =>
{
try
{
Log.Information("Start configured HttpClient for Wolt Adapter.");
Console.WriteLine("Start configured HttpClient for Wolt Adapter.");
var config = serviceProvider.GetRequiredService<IntegrationsConfig>();
var woltAdapterCredentials = config.Adapters["Wolt"].Credentials;
var woltUri = new Uri(hostContext.Configuration["WoltApi:BaseUrl"] ??
throw new InvalidOperationException("WoltUrl not found"));

client.BaseAddress = woltUri;
var byteArray =
Encoding.ASCII.GetBytes($"{woltAdapterCredentials.Username}:{woltAdapterCredentials.Password}");
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
Log.Information("END Successfully configured HttpClient for Wolt Adapter.");
Console.WriteLine("END Successfully configured HttpClient for Wolt Adapter.");
}
catch (Exception e)
{
Log.Error(e, "Failed wolt httpclient");
throw;
}
})
.AddPolicyHandler(GetRetryPolicy())
.AddPolicyHandler(GetCircuitBreakerPolicy());
Jimmacle
Jimmacle4w ago
i've already seen that code, i mean woltadapter itself this is just configuring a httpclientfactory
Dachi
DachiOP4w ago
services.AddTransient<GlovoAdapter>(); services.AddTransient<WoltAdapter>(); I do this right after i wrote AddHttpClient
Jimmacle
Jimmacle4w ago
let's try again
Dachi
DachiOP4w ago
you want me to run?
Jimmacle
Jimmacle4w ago
what code in WoltAdapter, like in the constructor, receives a http client from DI?
Dachi
DachiOP4w ago
public class WoltAdapter( ILogger<WoltAdapter> logger, IProductRepository productRepository, HttpClient httpClient, IntegrationsConfig integrations) : IIntegrationAdapter { here i inject HttpClient httpClient if you want i can call you and share screen
Jimmacle
Jimmacle4w ago
i just want to see evidence that the httpclient is the problem and not something else are you sure you're getting 2 hosted services from this code when both adapters are enabled?
Dachi
DachiOP4w ago
I also had that quesiton but when i look that up, it said that if the service is not properly configured it might not start up and it will stay silent (not throw erros)
Jimmacle
Jimmacle4w ago
but you can add logging for when the service successfully starts up
Dachi
DachiOP4w ago
i do log every setp
Jimmacle
Jimmacle4w ago
so you know for a fact that you end up with 2 hosted services running when you're using both adapters?
Dachi
DachiOP4w ago
that s the thing, wolt adapter is not being registered and i htought its cuz http client is not registered correctly
Jimmacle
Jimmacle4w ago
if that was the case, you would get an exception there is a reason i'm asking you to check that you actually get 2 hosted services
Dachi
DachiOP4w ago
how can i check? for loop does not throw an error
c#
IIntegrationAdapter adapter = adapterName.ToUpperInvariant() switch
{
"WOLT" => provider.GetRequiredService<WoltAdapter>(),
"GLOVO" => provider.GetRequiredService<GlovoAdapter>(),
_ => throw new NotSupportedException($"The adapter '{adapterName}' is not supported.")
};

var loggerFactory = provider.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger<ScheduledIntegrationWorker>();
return new ScheduledIntegrationWorker(logger, adapter, adapterConfig);
c#
IIntegrationAdapter adapter = adapterName.ToUpperInvariant() switch
{
"WOLT" => provider.GetRequiredService<WoltAdapter>(),
"GLOVO" => provider.GetRequiredService<GlovoAdapter>(),
_ => throw new NotSupportedException($"The adapter '{adapterName}' is not supported.")
};

var loggerFactory = provider.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger<ScheduledIntegrationWorker>();
return new ScheduledIntegrationWorker(logger, adapter, adapterConfig);
Jimmacle
Jimmacle4w ago
log from inside the worker when it starts up you said you log every step
Dachi
DachiOP4w ago
yeah i log it and wolt does not appear
Jimmacle
Jimmacle4w ago
so what does that tell you
Dachi
DachiOP4w ago
2025-09-07 16:58:03 [12:58:03 INF] [] Scheduled worker for 'Glovo' is starting with a 1 minute interval. there has to be same but for Wolt
Jimmacle
Jimmacle4w ago
which means... you are only ever registering one hosted service with this code
Dachi
DachiOP4w ago
its not starting up or it is being overriden by glovo
Jimmacle
Jimmacle4w ago
there is nothing wrong with the woltadapter
Jimmacle
Jimmacle4w ago
Stack Overflow
Multiple Instances of HostedService
I want to run multiple instances of the same hosted service. I tried registering them twice: services.AddHostedService&lt;MyService&gt;(); services.AddHostedService&lt;MyService&gt;(); But Execut...
Dachi
DachiOP4w ago
"I want to run multiple instances of the same hosted service" i have different instances. how does that relate to my problem?
Jimmacle
Jimmacle4w ago
you don't you're trying to register 2 hosted services both of type ScheduledIntegrationWorker and the linked article (and the articles it links to) explains the problem with that it also matches the behavior you're seeing, where only one hosted service ever works at a time
Unknown User
Unknown User4w ago
Message Not Public
Sign In & Join Server To View
Dachi
DachiOP4w ago
@Jimmacle Thanks man, fixed that bug

Did you find this page helpful?