Using Linq2Couchbase with ASP.NET Web API project

@molexmat

The example you are using is assuming that you have a dependency injection system configured, which is creating and injecting the BucketContext into the controller. You have a couple of options.

First, you can change the constructor on your controller so that it has no parameters. Instead of accepting the BucketContext as a constructor parameter, just create the BucketContext within the constructor. This is a perfectly valid approach, it’s just difficult to unit test.

The other option is to setup dependency injection in MVC. It’s more work up front, but IoC has lots of advantages with regard to testing and maintenance. I typically use Ninject. Adding the Ninject.Web.MVC nuget package will integrate MVC with Ninject. Then you just need to define globally how you want the BucketContext created when it is needed.

As an example, you could add a NinjectModule to your web application, which performs the registration:

using Ninject;
using Ninject.Modules;
using Ninject.Web.Common;

public class NinjectRegistration : NinjectModule
{
    public override void Load()
    {
        this.Bind<BucketContext>()
            .ToMethod(context => new BucketContext(ClusterHelper.GetBucket("default")))
            .InRequestScope();
    }
}

This example will always fill a BucketContext on the constructor of a controller with an instance pointed to the “default” bucket. It will also only create one instance per page request, so if you are also injecting into your backend service classes they will share the instance.

There are also more advanced options, especially if you are working against multiple buckets in your application. Let me know if you want some pointers on that.

Brant