2

I'm trying to create a typed http client in an Azure function through DI, when I set it like below, it is not getting into the lambda and therefore is not setting the BaseAddress.

        builder.Services.AddSingleton<IService, Service>();
        builder.Services.AddHttpClient<IService, Service>(client => {
            client.BaseAddress = new Uri("http://www.google.com");
        });

In the service that will create the methods for the client, it consumes like so:

  public Service(HttpClient client){

Then in other classes I'm injecting in Startup as:

  public AClass(Service service){

I'm following the official doc, what could be wrong?

0

1 Answer 1

5

This code snippet

builder.Services.AddHttpClient<IService, Service>(client => {
    client.BaseAddress = new Uri("http://www.google.com");
});

will already add the service to the collection. I would suggest removing the singleton

builder.Services.AddSingleton<IService, Service>();

Lastly, the service was registered with an abstraction, yet you try to inject the implementation.

public AClass(Service service){

I would suggest injecting the abstraction instead where needed

public AClass(IService service){ //<-- NOTE THE INTERFACE
Sign up to request clarification or add additional context in comments.

2 Comments

Indeed the problem was solved by removing the manual singleton. Thanks!
Thanks so much for this! I can't see any mention of this behaviour in the docs. It'd be nice if an Exception got thrown upon adding twice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.