Dependency Injection is a design pattern that makes coding easier. It saves you the hassle of instantiating objects with complex dependencies, and it makes it easier for you to write tests. With the Couchbase.Extensions.DependencyInjection library (GitHub), you can use Couchbase clusters and buckets within the ASP.NET Core dependency injection framework.

In my last blog post on distributed caching with ASP.NET, I mentioned the DependencyInjection library. Dependency injection will be explored in-depth in this post. Feel free to follow along with the code samples I’ve created, available on GitHub.

Basic setup of Couchbase

First, you’ll need a Couchbase Server cluster running. You can:

Next, you’ll need to create a bucket in Couchbase. This can be the “travel-sample” bucket that comes with Couchbase, or a bucket that you create yourself.

If you are using Couchbase Server 5.0, you’ll also need to create a user. Give that user Cluster Admin permission, and give it the same name as the bucket, just to keep things simple if you are following along.

Dependency Injection with Couchbase.Extensions

The Couchbase.Extensions (GitHub) project aims to make working with Couchbase Server and ASP.NET Core simpler. Dependency Injection is just one of these extensions.

You can add it to your ASP.NET Core project with NuGet:

  • By using Package Manager: Install-Package Couchbase.Extensions.DependencyInjection -Version 1.0.2
  • With the NuGet UI
  • Use the .NET command line: dotnet add package Couchbase.Extensions.DependencyInjection --version 1.0.2

(Version 1.0.2 is the latest version at the time of writing).

Couchbase extension for dependency injection on NuGet

Next, you’ll need to make changes to your Startup class in Startup.cs.

In the blog post on caching, I hard-coded the configuration:

This is fine for demos and blog posts, but you’ll likely want to use a configuration file for a production project.

Assuming you’re using the default appsettings.json, update that file to add a Couchbase section:

By making a “Couchbase” section, the dependency injection module will read right from the appsettings.json text file.

Constructor Injection

After dependency injection is setup, you can start injecting useful objects into your classes. You might inject them into Controllers, services, or repositories.

Here’s an example of injecting into HomeController:

Next, let’s do a simple Get operation on a well-known document in “travel-sample”. This token usage of the Couchbase .NET SDK will show dependency injection in action. I’ll make a change to the generated About action method. In that method, it will retrieve a route document and write out the equipment number.

And the result is:

Travel sample output of a single route

Success! Dependency injection worked, and we’re ready to use a Couchbase bucket.

If you aren’t using “travel-sample”, use a key from your own bucket.

Named buckets

You can use dependency injection for a single bucket instead of having to specify the name each time.

Start by creating an interface that implements INamedBucketProvider. Leave it empty. Here’s an example:

Then, back in Startup.cs, map this interface to a bucket using AddCouchbaseBucket:

Now, the ITravelSampleBucketProvider gets injected instead of the more general provider.

More complex dependency injection

Until this point, we’ve only used dependency injection on Controllers. Dependency injection starts to pay dividends with more complex, deeper object graphs.

As an example, imagine a service class that uses a Couchbase bucket, but also uses an email service.

Next, let’s use this service in a controller (aka making it a dependency). But notice that the controller is not directly using either the bucket or the email service.

If I were to instantiate ComplexService manually, I would have to instantiate at least two other objects. It would look something like: new ComplexService(new BucketProvider(), new MyEmailService(). That’s a lot that I have to keep track of, and if any dependencies change, it’s a lot of manual maintenance.

Instead, I can have ASP.NET Core use dependency injection to do all this for me. Back in Startup:

Now, ASP.NET Core knows how to instantiate:

  • ITravelSampleBucketProvider, thanks to Couchbase.Extensions.DependencyInjection
  • IEmailService – I told it to use MyEmailService
  • IComplexService – I told it to use ComplexService

Finally, when ApproveController is instantiated, ASP.NET Core will know how to do it. It will create ComplexService by instantiating MyEmailService and ComplexService. It will inject ComplexService automatically into `ApproveController’s constructor. The end result:

Complex service in action using dependency injection

For the complete example, be sure to check out the source code that accompanies this blog post on GitHub.

Cleaning up

Don’t forget to clean up after yourself. When the ASP.NET Core application is stops, release any resources that the Couchbase .NET SDK is using. In the Configure method in Startup, add a parameter of type IApplicationLifetime:

Within that Configure method, setup an ApplicationStopped event:

Summary

Dependency injection is a rich subject. Entire books have been written about it and its benefits to your application. This blog post just scratched the surface and didn’t even cover the testability benefits.

Couchbase.Extensions.DependencyInjection makes it easier to inject Couchbase into ASP.NET Core.

If you have questions or comments, make sure to check out the GitHub repository or the Couchbase .NET SDK forums.

And please reach out to me with questions by leaving a comment below or finding me on Twitter @mgroves.

Author

Posted by Matthew Groves

Matthew D. Groves is a guy who loves to code. It doesn't matter if it's C#, jQuery, or PHP: he'll submit pull requests for anything. He has been coding professionally ever since he wrote a QuickBASIC point-of-sale app for his parent's pizza shop back in the 90s. He currently works as a Senior Product Marketing Manager for Couchbase. His free time is spent with his family, watching the Reds, and getting involved in the developer community. He is the author of AOP in .NET, Pro Microservices in .NET, a Pluralsight author, and a Microsoft MVP.

12 Comments

  1. when trying to set
    ervices.AddCouchbase(Configuration.GetSection(“Couchbase”));
    using settings the call to : Configuration.GetSection(“Couchbase”))
    returns null.

    1. So this is not the issue ..
      seems that data passed corecttly but when i try to call:
      bucketProvider.GetBucket(“statistics”, “”);
      i get “Bootsrap exception”

      1. Arthur, would you mind posting your question along with a more complete view of your code in the Couchbase .NET forum: https://www.couchbase.com/forums/c/net-sdk

  2. Hi Matthew, could you please update the repository code? I am having troubles to use it in an ASP.Net Core 2.2 project.

    1. Sure, Lahbabi, I just updated the repository to .NET Core 2.2. It’s likely you were not actually having issues with .NET Core 2.2. My guess is that you are using Couchbase Server 5 or newer, which changed the way that authentication works. (The only .NET Core issue I saw is that I had some loggerFactory stuff in there that has been deprecated since .NET Core 1).

  3. Thanks Matthew, it works, I could authenticate but could not find where to click to fetch data ? the travel-sample is already installed in the database.

    1. Since I’ve seen your wonderful simple CRUD Gifts list sample, I was expecting to see a similar thing but this time using Dependency Injection. How can I get such crud with Dependency Injection ?

      1. You’re right that this sample doesn’t cover all of the CRUD operations, but the SDK hasn’t changed much since I made the video you’re referring to. If you check out HomeController in this repository, you’ll see that it’s still just an IBucket object being used. https://github.com/couchbaselabs/blog-source-code/blob/master/Groves/078AspNetCoreDependencyInjection/src/CouchbaseDIExample/CouchbaseDIExample/Controllers/HomeController.cs#L42

        Would you be interested in a video showing .net core 2.2, dependency injection, crud, with Couchbase all together?

        1. I would not go to the point of asking you that :) I guess putting the Dependency Injection in action with Rest API in the wishlist demo even just by modifying the existing code would be very helpful to me, and to a lot of .Net Core developers wanting to touch and appreciate dealing with Couchbase, The Wishlist code sample with the N1QL introductory is a very simple and very concise crud starting point to push Couchbase to more popularity into .Net Core developers community, the current sample is a bit complicated with its ComplexService and EmailService, etc .. for those who just want to start.

          1. Thank you, that’s good feedback. I haven’t updated my ‘getting start’ ASP.NET content in a while, it might be time.

Leave a reply