1

Documentation says to use builder.Services.AddHttpClient() for registration HttpClient but I can resolve HttpClient without this.

I have a small startup where only register MyService :

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddTransient<MyService>();
    }
}

and in Function, I want to resolve HttpClient and MyService and this code works.

public class Function
{
    public Function(MyService service, HttpClient client)
    {
    }

    [FunctionName("func")]
    public async Task<IActionResult> Update(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]
        HttpRequest request,
        ILogger logger)
    {
        return new OkObjectResult("Hello");
    }
}
  • Who and where are register HttpClient?
  • Should I use builder.Services.AddHttpClient()? Is this not redundant?

1 Answer 1

6

You are right. You first need to register to it to the services:

public class Startup : FunctionsStartup
{
    public override void Configure(IFunctionsHostBuilder builder)
    {
        //Register HttpClientFactory
        builder.Services.AddHttpClient();

        builder.Services.AddTransient<MyService>();
    }
}

If your Service will use the HttpClientFactory it is important to be register before the service. So when the MyService instance depedencies will be resolved there will already be a record for HttpCliendFactory in the DI container.

Your Function.cs class will then be:

public class Function
{
    private IHttpClientFactory _httpClientFactory;
    private MyService _myService;


    public Function(MyService myService, IHttpClientFactory client)
    {
        _myService = myService;
        _httpClientFactory = httpClientFactory;
    }

    [FunctionName("func")]
    public async Task<IActionResult> Update(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]
        HttpRequest request,
        ILogger logger)
    {
        //How to use example
        var client = _httpClientFactory.CreateClient();

        return new OkObjectResult("Hello");
    }
}

HttpClient of course can be used without the client factory, but if you spawn HttpClient objects from the HttpClientFactory you will have a better out of the box management of your HttpClient resources.

Sign up to request clarification or add additional context in comments.

1 Comment

Did it work for you? Do you need further assistance?

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.