Skip to content
This repository was archived by the owner on Nov 17, 2018. It is now read-only.
This repository was archived by the owner on Nov 17, 2018. It is now read-only.

AddHttpClient should still work even if called before AddSingleton #162

@joshlangs

Description

@joshlangs
	class Program
	{
		//<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.1.1" />
		//<PackageReference Include = "Microsoft.Extensions.Http" Version="2.1.1" />
		class Blarg
		{
			public Blarg(HttpClient c) { }
		}
		static void Main(string[] args)
		{
			ServiceCollection sc = new ServiceCollection();
			sc.AddSingleton<Blarg>();
			sc.AddHttpClient<Blarg>();
			sc.BuildServiceProvider().GetRequiredService<Blarg>(); // OK

			sc = new ServiceCollection();
			sc.AddHttpClient<Blarg>();
			sc.AddSingleton<Blarg>();
			sc.BuildServiceProvider().GetRequiredService<Blarg>(); // System.InvalidOperationException: 'Unable to resolve service for type 'System.Net.Http.HttpClient' while attempting to activate 'ConsoleApp3.Program+Blarg'.'
		}
	}

In the project above, the first service provider works without any problem. But the second one crashes with an exception.

I got trapped by this. I didn't realize that I needed to call AddSingleton before I called AddHttpClient or else I would get an exception. Took me a while to figure it out.

I don't know why it makes a difference. Maybe there's a reason? But if not, it would probably better to make it work either way.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions