Maybe it will help, but in my situation this worked:
public void ConfigureServices(IServiceCollection services){ services.AddTransient<IMyService,MyService>(); // my usual DI injection of a service that can be mocked services.AddHttpClient<IMyService,MyService>(client => { client.BaseAddress = new Uri("https://myservice.com/api"); }); // notice that I use IMyService for the reference of the registration AND implementation to where it will be injected.}public class MyService{ public MyService(HttpClient client) { // client.BaseAddress is properly set here }}public class MyController : Controller{ public MyController(IMyService service) // used by the interface {}}
I've tried services.AddHttpClient<IMyService>()
as well, which would not resolve due to lack of it's constructor.Also tried services.AddHttpClient<MyService>()
as above, but it would not resolve the configured instance, as described above.
So the important part is that class that is used to reference the resolved type needs to be used. So this also works:
public void ConfigureServices(IServiceCollection services){ services.AddTransient<MyService>(); // registering the type itself, not via interface services.AddHttpClient<MyService>(client => { client.BaseAddress = new Uri("https://myservice.com/api"); }); // it's ok here, since it will be resolved by it's own type name}public class MyService{ public MyService(HttpClient client) { // client.BaseAddress is properly set here }}public class MyController : Controller{ public MyController(MyService service) // used by the type directly {}}
It kind of makes sense, but documentation and examples could be better.