C#
Dependency Injection
.NET Core
HttpClient
IServiceCollection

IServiceCollection does not contain a definition for AddHttpClient

Codemia Knowledge Hub ·

Add using Microsoft.Extensions.DependencyInjection; to the source file, or add a reference to the Microsoft.Extensions.Http NuGet package in the project that contains the call. AddHttpClient is an extension method, so the compiler only finds it when both the namespace import and the assembly reference are present.

Why the error message is misleading

Extension methods look like instance methods at the call site, but the compiler resolves them differently. An extension method is a static method in a static class, and it is discoverable only when that class's namespace is imported with a using directive.

AddHttpClient is defined in Microsoft.Extensions.DependencyInjection.HttpClientFactoryServiceCollectionExtensions, which lives in the Microsoft.Extensions.Http assembly. When the compiler cannot find the extension, it reports the error as if IServiceCollection itself lacked the method:

 
error CS1061: 'IServiceCollection' does not contain a definition for 'AddHttpClient'
and no accessible extension method 'AddHttpClient' accepting a first argument of type
'IServiceCollection' could be found

The second half of the message points at the real problem: "no accessible extension method could be found."

Fix 1: Add the using directive

This is the most common fix. The source file that calls AddHttpClient must import the namespace:

csharp
using Microsoft.Extensions.DependencyInjection;

That single line fixes most cases, because ASP.NET Core web projects already reference the Microsoft.Extensions.Http assembly through the shared framework. Even with the package installed, the compiler cannot see the method without this import.

Before

csharp
1// Missing using directive
2var builder = WebApplication.CreateBuilder(args);
3builder.Services.AddHttpClient("github", client =>
4{
5    client.BaseAddress = new Uri("https://api.github.com/");
6});
7// Compiler error: CS1061

After

csharp
1using Microsoft.Extensions.DependencyInjection;
2
3var builder = WebApplication.CreateBuilder(args);
4builder.Services.AddHttpClient("github", client =>
5{
6    client.BaseAddress = new Uri("https://api.github.com/");
7});
8// Compiles successfully

Fix 2: Add the NuGet package reference

If the using directive does not fix it, the project is missing a reference to the assembly that contains the extension method.

.NET CLI

bash
dotnet add package Microsoft.Extensions.Http

.csproj file

xml
1<Project Sdk="Microsoft.NET.Sdk">
2  <PropertyGroup>
3    <TargetFramework>net8.0</TargetFramework>
4  </PropertyGroup>
5
6  <ItemGroup>
7    <PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
8  </ItemGroup>
9</Project>

Package Manager Console (Visual Studio)

powershell
Install-Package Microsoft.Extensions.Http

Then restore dependencies and rebuild:

bash
dotnet restore
dotnet build

The package is not usable until dotnet restore runs. Most IDEs restore automatically, but CI pipelines may not.

Which fix each project type needs

Project TypeNamespace Import Needed?Package Reference Needed?
ASP.NET Core Web AppYesNo (included via shared framework)
ASP.NET Core Web APIYesNo (included via shared framework)
Class Library targeting .NET 8+YesYes
Console ApplicationYesYes
Worker ServiceYesUsually no (included in template)
Blazor ServerYesNo (included via shared framework)
xUnit / NUnit Test ProjectYesYes

ASP.NET Core web projects reference the Microsoft.AspNetCore.App shared framework, which includes Microsoft.Extensions.Http. Class libraries, console apps and test projects do not, so they need an explicit package reference.

The multi-project trap

This catches experienced developers. Consider a solution like this:

 
1MySolution/
2  MyApi/           (ASP.NET Core Web API)
3    Program.cs
4    MyApi.csproj   (references Microsoft.AspNetCore.App)
5  MyApi.Core/      (Class Library)
6    ServiceRegistration.cs
7    MyApi.Core.csproj   (does NOT reference Microsoft.Extensions.Http)

If ServiceRegistration.cs in the class library calls AddHttpClient, the build fails even though the web project has the shared framework reference. Compilation happens per project, so the class library needs its own reference, not just the startup project:

xml
1<!-- MyApi.Core.csproj -->
2<Project Sdk="Microsoft.NET.Sdk">
3  <PropertyGroup>
4    <TargetFramework>net8.0</TargetFramework>
5  </PropertyGroup>
6
7  <ItemGroup>
8    <PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
9  </ItemGroup>
10</Project>

This is the most common cause of the error in real codebases with clean architecture or layered project structures.

Also keep Microsoft.Extensions.Http versions aligned across the solution. If one project references 8.0.0 and another 6.0.0, binding redirects or runtime errors can occur.

Verify the fix with a minimal program

If this minimal program compiles, the extension method is available and the problem in your application is project-specific, not environmental:

csharp
1using System;
2using Microsoft.Extensions.DependencyInjection;
3
4var services = new ServiceCollection();
5
6services.AddHttpClient("example", client =>
7{
8    client.BaseAddress = new Uri("https://api.example.com/");
9    client.DefaultRequestHeaders.Add("Accept", "application/json");
10    client.Timeout = TimeSpan.FromSeconds(30);
11});
12
13Console.WriteLine("HttpClient registered successfully.");

Named vs typed clients

Once the error is gone, there are two main ways to register HTTP clients. Either is better than calling new HttpClient() directly, which bypasses handler lifetime management and can exhaust sockets under load.

Named clients

Named clients are identified by a string key:

csharp
1services.AddHttpClient("payments", client =>
2{
3    client.BaseAddress = new Uri("https://payments.example.com/");
4});
5
6services.AddHttpClient("inventory", client =>
7{
8    client.BaseAddress = new Uri("https://inventory.example.com/");
9});

Consumers request a client by name through IHttpClientFactory:

csharp
1public class OrderService
2{
3    private readonly IHttpClientFactory _factory;
4
5    public OrderService(IHttpClientFactory factory) => _factory = factory;
6
7    public async Task ProcessOrderAsync()
8    {
9        using var client = _factory.CreateClient("payments");
10        var response = await client.GetAsync("status");
11    }
12}

Typed clients

Typed clients bind configuration to a specific class:

csharp
1public class PaymentsClient
2{
3    private readonly HttpClient _http;
4
5    public PaymentsClient(HttpClient http)
6    {
7        _http = http;
8    }
9
10    public async Task<string> GetStatusAsync(CancellationToken ct)
11    {
12        return await _http.GetStringAsync("status", ct);
13    }
14}
15
16// Registration
17services.AddHttpClient<PaymentsClient>(client =>
18{
19    client.BaseAddress = new Uri("https://payments.example.com/");
20});

They are injected directly, without IHttpClientFactory:

csharp
1public class OrderService
2{
3    private readonly PaymentsClient _payments;
4
5    public OrderService(PaymentsClient payments) => _payments = payments;
6}
FeatureNamed ClientsTyped Clients
RegistrationString keyClass type
InjectionVia IHttpClientFactoryDirect injection
Compile-time safetyNo (string key)Yes (type checked)
Configuration co-locationSeparate from usageNext to the client class
Best forMany simple endpointsDedicated service clients

Adding delegating handlers

A common next step is adding cross-cutting concerns such as logging, retry or authentication:

csharp
1services.AddHttpClient<PaymentsClient>(client =>
2{
3    client.BaseAddress = new Uri("https://payments.example.com/");
4})
5.AddHttpMessageHandler<AuthTokenHandler>()
6.SetHandlerLifetime(TimeSpan.FromMinutes(5));

These methods are also extension methods from Microsoft.Extensions.Http, so they become available once the package reference and namespace import are in place.


Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Object-Oriented Design practice on Codemia

Turn requirements into classes, and defend the design, on the problems that come up in OOD rounds.

Practice OOD