-
Notifications
You must be signed in to change notification settings - Fork 46
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
ASP.NET Best Practices? #117
Comments
// Program.cs
builder.Services.AddSingleton(new PostmarkClient(builder.Configuration["PostmarkServerToken"]));
// MyController.cs
public MyController(PostmarkClient postmarkClient) {
// Initialize Postmark client
_postmarkClient = postmarkClient;
} |
Postmark-dotnet internally uses a static instance of |
This is an anti-pattern. The clients are a thin layer on top of a message handler pool that handles the actual HTTP connections. The Http clients themselves are basically just thin wrappers to freely create/destroy with transient scope. All the heavy lifting is done in the message handlers whose lifetime is managed by the pool internal to the If instead you use a static HttpClient then the handler is never allowed to return to the pool for as long as the application is running. This also means the handler, once stale, can never close and be refreshed. Among other things this means e.g. underlying DNS changes never propagate. It can lead to incredibly hard to diagnose 'random' network failures of a non-transient nature - that are instantly resolved by killing and restarting an application only to return at another 'random' future moment. If this library is using an internal static field holding an HttpClient, then it is 'doing it wrong,' irrefutably. |
Thank you @rjgotten . As someone who is fairly newish at C# and .net, I only knew how to create http clients for asp.net but could never give such a fabulous answer on why it's done so which is why I asked my question to begin with. |
@elibroftw That said, I just had a slightly deeper look and... yikes. This type of thing really needs to be Normally you wouldn't have to worry about that because |
Is it better to create a new postmark client for each controller, or should we be using a Singleton or something like that and create only one client?
For reference, Microsoft tutorials for MongoDB creates a service for a collection and uses that service/singleton to insert/get.
The text was updated successfully, but these errors were encountered: