Search code examples
c#.net.net-corehttpclient

What is the suggested way to create HttpClient object in long running worker service


I am working on worker service which has a separate class DAL for getting/posting data using HttpClient. DAL has several methods, in every method HttpClient object has different param/values.

One way is to create object in every method of DAL.

Other way is creating in constructor of DAL but not sure while switching between methods how HttpClient object is overlapping the already assigned values.

Please suggest.


Solution

  • in every method HttpClient object has different param/values.

    Nope, it does not. It may have different default values, but the values of a REQUEST can be set in a REQUEST.

    One way is to create object in every method of DAL.

    Also known as: Ignoring everything in the documentation and published by the team about NOT doing this.

    Other way is creating in constructor of DAL

    Same as before.

    Make ONE (!) that is used over and over. Not ONLY from the DAL. Generating a HttpClient is expensive and they are reusable - or better, go all documentation and grab one (repeatedly) from a HttpClientFactory that will neutralize the overhead of creating one (because it isnot actually the HttpClient htat is expensive but the creation of the inner messaging stack).

    Then set all parameters etc. - in the messages.