-
Notifications
You must be signed in to change notification settings - Fork 22
Description
There are a few potential memory leaks and deferred garbage collection cycle that I identified. I thought of bringing this to community's notice. Also, I will take this opportunity to suggest some better coding practices.
- The following classes implement the
IDisposableinterface. If we don't call theDisposemethod on them ourselves, then we potentially leave it to the garbage collector to dispose of and then cleanup the memory. This typically happens in 2 cycles of garbage collection(The garbage collector has 3 cycles). However, if we call thedisposemethod ourselves before exiting a block scope, the garbage collector will then take just one cycle to clean up the memory and end up doing less work. We have to remind ourselves that garbage collection is a very expensive process).
HttpResponseMessage - Docs
HttpRequestMessage - Docs
HttpClient - Docs
- Newing up the
HttpClientin the construction is typically a bad practice. It is always better to rely on Dependency Injection. The typical way to implement it is using this would be to acceptIHttpClientFactoryin the constructor.
IHttpClientFactory - Docs
then add dependency injection to inject a version of the IHttpClientFactory.
Microsoft.Extensions.DependencyInjection - Nuget
then create a ServiceCollectionExtensions static class and create a method like this -
// Clients of this Nuget package need to utilize this before using the classes.
public static IServiceCollection AddAppWrite(this IServiceCollection serviceCollection, IConfiguration configuration)
{
// This should add the IHttpClientFactory that you want to register with proper retry policies using Poly.NET
// This method should also house any other interface and class registrations with the DI system that are needed.
// If it were me, I would also implement an IAppWriteUriProvider which has methods that returns the URI of all the areas that are needed and inject an implementation here.
}
and then use the IHttpClientFactory.CreateClient method to create the actual HttpClient. This typically is also an extension method. Not the HttpClient is a class that needs eager disposing.
IHttpClientFactory.CreateClient - Docs
Also, I would never expose the underlying HttpResponseMessage directly to the consumer, but instead return the string and let abstract away any other Http only resemblance. The reason I say this is because tomorrow you guys might implement the APIs using gRPC but to the consumer, it should not feel like anything has changed.
I apologize for all the ranting. My only intention is to really help the community with whatever knowledge I have.