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?