0
votes

If I have a scoped service:

services.AddSingleton<MyScopedService>();

And in that service, an HTTP request is made:

HttpClient client = _clientFactory.CreateClient();
StringContent formData = ...;
HttpResponseMessage response = await client.PostAsync(uri, formData);
string data = await response.Content.ReadAsStringAsync();

I read here that for an AddScoped service, the service scope is the SignalR connection.

If the user closes the browser tab before the response is returned, the MyScopedService code still completes.

Could someone explain what happens to that MyScopedService instance? When is it considered out of scope? After the code completes? Is the time until it's garbage collected predictable?

I have a Blazor-server project using scoped dependency injections (fluxor, and a CircuitHandler), and I'm noticing that the total app memory increases with each new connection (obviously), but takes a while (minutes) for the memory to come down after the browser tabs are closed.

Just wondering if this is expected, or if I could be doing something to let the memory usage recover more quickly. Or maybe I'm doing something wrong with my scoped services.

1
Yes, this is expected...What you're experiencing is normal . " if I could be doing something to let the memory usage recover more quickly". No, don't do anything... memory allocation will grow up until no memory is available, which will force the GC to run and clean up... - enet
Are you disposing the hub connection? I have seen this before. Dispose the hub connection by adding IDisposable or IDisposableAsync to your service. - Brian Parker
Your Service is a Singleton, it is not Scoped at all. - Henk Holterman

1 Answers

0
votes

Add IDisposeAsync to your service then in your service :

public async ValueTask DisposeAsync() => await hubConnection.DisposeAsync();

This was copied from one of my own libraries I was facing the same issue. GC will not work if there are references to other objects...