I'm working on a windows service. Code of windows service is very simple but it has a strange manner!
In windows service I should call a WebApi each 20 seconds and save the result in a SQL Database
I'm using autofac to creat instance of HttpClient at Program.cs

// HttpClient
builder.Register(ctx =>
    var httpClient = new HttpClient
        BaseAddress = new Uri(StaticAssets.WebApiBaseAddress)
    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    return httpClient;

I never dispose httpClient instance manually.
After running the windows service about 8 hours, IIS not work and we can not remote to server anymore, we tested Windows Remote Desktop Connection, VNC(we have VNC on server) ...
We could remote to server with KVM and stop the windows service and every thing go back. I think this problem maybe related to httpClient instance.
Are you already see the problem? How could you resolve it?

2 Answers 2


HttpClient is unfortunately Disposable but it should not have been. Your problem is probably due to windows running of connections or a connection limit for service point manager

In any case the solution is to just make the instance static. This is not obvious since the interface is disposable.

  • Can static HttpClient be used for requests with different authentication data(tokens for example)?
    – Fabio
    Commented Jul 18, 2018 at 6:24
  • Yes. You would just have to use SendAsync() instead of GetAsync. After you instantiate HttpRequestMessage you can add headers. You can also choose to use 5 or 10 static HttpClients. That is also fine. Just not a new one for each request. Commented Jul 18, 2018 at 7:22

If you only have one of them? nothing.

If you create a new one per request you will run into problems as each consumes an open port. Although you would have to look into whether your DI framework automatically disposes of them

If you create a new one per request AND dispose of it, you will also run into problems as the dispose doesn't actually free up the open port


  • My application is Windows Service, I don't have any requests. So I have to check if autofac dispose it. Commented Jul 18, 2018 at 12:46

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.