IBucket lifetime in .NET SDK 2.0

Hello,

The .NET SDK 2.0 documentation clearly states that the ICluster object is thread safe and a single instance should be reused across the entire application. On the other hand the Java SDK documentation explicitly states that both the cluster and bucket instances are thread safe and can be long lived and reused across the entire application.

Assuming that my ASP.NET application works with only one bucket, can I reuse a bucket instance?

For example in my Application_Start I would create a singleton bucket and reuse it across my application:

public static ICluster Cluster;
public static IBucket Bucket;

protected void Application_Start(object sender, EventArgs e)
{
    Cluster = new Cluster("couchbaseClients/couchbase");
    string bucketName = Cluster.Configuration.BucketConfigs.Single().Key;
    Bucket = cluster.OpenBucket(bucketName);
}

protected void Application_End(object sender, EventArgs e)
{
    Cluster.CloseBucket(bucket);
    Cluster.Dispose();
}

Initially I was opening and closing the bucket from the cluster instance for every operation I wanted to perform but I noticed that the cluster.OpenBucket method is very slow and I thought that reusing the bucket instance would be fine. Is this a correct approach and is it how the SDK is supposed to be used?

Thanks in advance.

@dimitrod -

Yes, this will work, both ICluster and IBucket implementations are thread-safe. Also, checkout the ClusterHelper class; it’s a singleton for a cluster and a multiton for buckets. It has been updated in release 2.0.2. So, if you need to use more than one bucket in your application, it will cache them for you and there is no need to explicitly add the static variable to your global.asax.

//create a config - this is just a default config for localhost
var clientConfig = new ClientConfiguration();

//initialize the cluster - this would be done in Application_Start
ClusterHelper.Initialize(clientConfig);

//open a bucket and get the reference
var bucket1 = ClusterHelper.GetBucket("default");
var bucket2 = ClusterHelper.GetBucket("default");
 
//The two are the same
Assert.AreSame(bucket1, bucket2);

As long as you don’t call Dispose() on the bucket, Remove(bucket) on the ClusterHelper, or Close the Cluster instance, you will have a managed long-lived IBucket reference. You can read more here: http://blog.couchbase.com/couchbase-.net-sdk-2.0.2-released

-Jeff

1 Like