You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Nov 17, 2018. It is now read-only.
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.