0

I'm using System.Net.Http.HttpClient to talk to a RESTful service in an MVC4 application on the back end. Depending on the user making the request the authentication header will be different for communication with the RESTful service, so the values to set in the header should be cached for each user. These values may change during a session's lifetime.

I am using StructureMap for DI. Some questions:

  1. According to this it sounds like there should be a single instance of HttpClient for all requests. Although some say directly injecting the HttpClient may be a bad idea due to it being IDisposabe, others say that it's not necessary to dispose it. So, what is the best way to inject HttpClient?
  2. Is it possible that the single instance of HttpClient can become disposed of or invalidated during run time (maybe the REST server reboots)? If so, then I think there is no choice in directly injecting HttpClient and it must be wrapped in a manager class that will check if the HttClient instance is valid and instantiate a new client if there's a problem. The issue is that I don't see a way make that test.
  3. Where is the best place to cache the user specific authentication header information? I don't think that passing the information to the service layer from the controller is clean, as it seems to be suggested here, so I'm thinking an HttpSession scoped injected object in the data layer is the way to go here, but would love to hear other ideas.
Community
  • 1
  • 1
Alex
  • 9,250
  • 11
  • 70
  • 81

1 Answers1

0

Create the HttpClient when your MVC4 application starts and dispose it when it shuts down. If the server you are calling with the HttpClient reboots that will not require you to create a new instance of HttpClient. TCP connections are managed independently under the covers by the ServicePointManager.

I don't understand your question regarding user specific auth information. Are you trying to get your MVC site to impersonate the user when you call to the RESTful service? If so, then just set the Auth header on each request.

Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
  • How exactly would you create/inject the singleton HttpClient - naked or with some manager/wrapper? Regarding setting the auth header, I am asking where to store/cache the user information that will be used when building the header value. In my case it's the authorization header, but could be applied to anything that needs to be submitted per user on each request. – Alex Oct 22 '13 at 14:49
  • I think I need to clarify that user information to pass to the header will be determined at the beginning of each new session. I will update my original question. – Alex Oct 22 '13 at 15:22
  • @Alex I would try and use HttpClient naked. It can be a pain to wrap HttpClient. – Darrel Miller Oct 22 '13 at 17:21