Skip to content

An async thread-safe singleton for a Twilio RestClient

License

Notifications You must be signed in to change notification settings

soenneker/soenneker.twilio.restclient

Repository files navigation

Soenneker.Twilio.RestClient

An async thread-safe singleton for a Twilio RestClient

Installation

dotnet add package Soenneker.Twilio.RestClient

Why?

This library provides a singleton of a TwilioRestClient.

Internally it implements an HttpClient singleton. This HttpClient has less overhead than new instances of HttpClient and IHttpClientFactory all while correctly handling connection pooling for DNS changes.

See soenneker.utils.httpclientcache for more information.

Usage

  1. Register ITwilioRestClientUtil with DI.
public static async Task Main(string[] args)
{
    ...
    builder.Services.AddTwilioRestClientUtilAsSingleton();
}
  1. Inject ITwilioRestClientUtil via constructor, and retrieve a TwilioRestClient.
public class TestClass
{
    ITwilioRestClientUtil _twilioRestClientUtil;

    public TestClass(ITwilioRestClientUtil twilioRestClientUtil)
    {
        _twilioRestClientUtil = twilioRestClientUtil;
    }

    public async ValueTask SendMessage()
    {
        var message = await MessageResource.CreateAsync(
            new PhoneNumber("+11234567890"),
            from: new PhoneNumber("+10987654321"),
            body: "Hello World!",
            client: await _twilioRestClientUtil.Get()
        );

        Console.WriteLine(message.Sid);
    }