Search code examples
xamarin.formslifecycleazure-cosmosdb

DocumentDb - DocumentClient Lifecycle Management


I am using Xamarin Forms with a Shared project to connect to a DocumentDB using Azure NOSQL DocumentDB. I have a service which connects to the database:

public class PaymentService : IPaymentService<Payment>, IDisposable

And so far I have been keeping a Class level property for the Client:

public DocumentClient Client { get; set; }

which I dispose of in the Dispose method.

In the constructor of the Service class I call a Connect method once and reuse it in all my methods for GetAll, GetSingle, Update, Delete etc.

public void Connect()
{
    try
    {
        if (Client == null)
        {
            Client = new DocumentClient(new Uri(SUBSCRIPTION_URL), PRIMARY_KEY);
        }    
    }
    catch (DocumentClientException de)
    {
        ...
    }
    catch (Exception e)
    {
        ...
    }
}

I have seen some articles where the DocumentClient is managed per request in a using statement per method.

public async Task<bool> Delete(string guid)
{
    using (var client = new DocumentClient(new Uri(SUBSCRIPTION_URL), PRIMARY_KEY))
    {
        var result = await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(DATABASE_ID, COLLECTION_ID, guid));

        var item = GetSingle(guid);
        if (item != null)
        {
            return false;
        }
        return true;
    }
}   

I have tried both methods but find using the using statement to be very slow.

My Question is: What is considered best practice for managing the Lifecycle of the DocumentClient?


Solution

  • DocumentClient shouldn't be used on per-request basis and instead you should use it as a singleton instance in your application. Creating client per-request will add lots of overhead on the latency.

    So I'd declare Client property as "static" and initialize it in the constructor of PaymentService. You could call await Client.OpenAsync() in the Connect method to "warm" up the client and in each of your public methods directly use the Client instance to call the DocumentDB APIs.

    Dispose the Client in the Dispose method of PaymentService.

    Could you please point to the articles where you saw that DocumentClient should be used per-request basis so that we can clarify it there as well?

    Hope that helps!