Click here to Skip to main content
15,887,477 members
Articles / Programming Languages / C#
Tip/Trick

Setting up CouchbaseClient to be used with IoC

Rate me:
Please Sign up or sign in to vote.
4.67/5 (2 votes)
29 Nov 2013CPOL2 min read 11.1K   3   1
Injecting servers, buckets and passwords into CouchbaseClient

Introduction

Couchbase is a fairly new NoSql, Key/Value storage platform that is built to extend MemCached by adding persistence, amongst other changes. My company has recently adopted Couchbase, and I was writing a new API service around it, and ran into a problem injecting the server urls, the bucket name, and the bucket password into the CouchbaseClient object.

I didn't want to use the built in Couchbase config sections because our build/deploy system doesn't deal with specialized sections in the web.config section very well, and personal preference. I would rather do as much of the initialization in code as possible.

This tutorial assumes you have knowledge of CouchbaseClient, and Inversion of Control/Dependency Injection strategies.

Using the Code

The code presented here is step by step instructions on preparing and using a class to inject a CouchbaseClient instance.

I also have created a CouchbaseUri class that takes a url of a Couchbase server, and formats it so that CouchbaseClient will work.

C#
public sealed class CouchbaseUri : Uri
{
    private const string BaseUrl = "http://{0}:8091/pools";

    public CouchbaseUri(string server)
        : base(string.Format(BaseUrl, server))
    {
    }
}

First, create an interface that inherits ICouchbaseClient. There is no need to add any methods or properties to it. Doing it this way will allow for the instance of the class created later in the tutorial to be injected as required.

C#
public interface IMyCouchbaseClient : ICouchbaseClient
{
}

Next, create a class that extends CouchbaseClient, and also inherits the interface that was created above. In this class, add a static method CreateConfiguration which takes the couchbaseServers, bucket, and bucketPassword and creates an ICouchbaseClientConfiguration instance. The couchbaseServers string is actually a comma delimited list of base urls for each server in the Couchbase cluster.

C#
public class MyCouchbaseClient : CouchbaseClient, IMyCouchbaseClient 
{
    private static ICouchbaseClientConfiguration CreateConfiguration(string couchbaseServers,
                                                                     string bucket,
                                                                     string bucketPassword)
    {
        var configuration = new CouchbaseClientConfiguration
                                {
                                    Bucket = bucket,
                                    BucketPassword = bucketPassword,
                                };

        couchbaseServers.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries)
                        .Select(url => new CouchbaseUri(url)).ToList()
                        .ForEach(couchbaseUrl => configuration.Urls.Add(couchbaseUrl));

        return configuration;
    }

    public MyCouchbaseClient (string couchbaseServers,
                              string bucket,
                              string bucketPassword)
        : base(CreateConfiguration(couchbaseServers, bucket, bucketPassword))
    {
    }
}

I have used this method with Castle.Windsor, and created extensions that actually find the servers, and bucket information in the .config file, but that is a little too messy to put here. Ninject is a little easier to demonstrate.

C#
public sealed class ServicesModule : NinjectModule
{
    public override void Load()
    {
        Bind<IMyCouchbaseClient>().ToMethod(x =>
            {
                return new MyCouchbaseClient(
                    ConfigurationManager.AppSettings["couchbaseServers"],
                    ConfigurationManager.AppSettings["bucket"]
                    ConfigurationManager.AppSettings["bucketPassword"]);
            }).InSingletonScope();
    }
} 

Couchbase client is now ready to be injected into classes as required.

C#
public sealed class MyRepository
{
    private readonly IMyCouchbaseClient _dataSource;

    public MyRepository(IMyCouchbaseClient dataSource)
    {
        if (dataSource == null) throw new ArgumentNullException("dataSource");

        _dataSource = dataSource;
    }
} 

What this class does is create a way of differentiating between CouchbaseClient instances. By making classes like this, it is now possible to have multiple CouchbaseClients in your application, pointing to different buckets.

History

  • Nov 29, 2013 - Initial submission

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) PNI Media
Canada Canada
I have been programming for 18 years, working in VB6 and C# mostly. It is a passion of mine to write good clean, readable code, and I strive to do it myself, and educate others on doing it.

Comments and Discussions

 
QuestionVery good article! Pin
Volynsky Alex30-Nov-13 6:49
professionalVolynsky Alex30-Nov-13 6:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.