In a web-request I want to do a call to another server using Microsoft HttpClient. I am using MVC4 (hosted in IIS), and castle-windsor as IOC-container. I read that the HttpClient is designed to live during serveral calls, and my question is how I should implement this.
I come up with a few options:
I would use
LifestyleTransient to create a new one for each request. That's safest when you're not sure that the class can function as a singleton.
It's also not a bad idea to depend on an abstraction (an interface) rather than on the HttpClient directly unless you're certain that the class would never be used apart from making HTTP requests. Even then it may make unit testing easier. That's one of the big benefits of using Windsor or another DI container. Otherwise there's not much benefit over just instantiating an
HttpClient directly in your class.
Update. I did some looking and found this answer indicating that an
HttpClient should be reused for a given API. It's highly upvoted and I don't see any dissent from experience (or otherwise) so I'm going to reference it when doing some near-term development.
I would implement this by defining a strongly-typed client class that implements an interface, and then depending on the interface in my classes (not directly on the client.) Then Windsor can create the class for an interface and maintain it as a singleton.