Skip to main content

Posts tagged with 'dependency injection'

Jeremy Miller has created an open-source IoC tool called Lamar. This episode is sponsored by Smartsheet.

Show Notes:

  • StructureMap has been sunsetted

  • Instead, consider Lamar for your IoC container needs.

  • Nested containers

  • At one point I was rambling about ASP.NET Core’s inability to use the service locator pattern. Some quick points:

    • Don’t use Service Locator, there are lots of other better patterns to use.

    • DO NOT DO IT.

    • If you absolutely need it: here’s a blog post about it.

    • I was incorrect in the podcast by making a sweeping statement about ASP.NET Core not having service locator. But for a very specific, narrow case where I wanted to use the service locator pattern recently, I was unable to do so. This might have been my own failing, or something that just isn’t possible with the built-in ASP.NET IoC. I have not tried this very specific, narrow use case with Lamar yet.

  • I plugged my book, AOP in .NET yet again.

  • Lamar is named after Mirabeau Lamar (a hero of the Texas revolution)

  • Paper: Inversion of Control Containers and the Dependency Injection pattern by Martin Fowler

  • Gitter room for Lamar

Want to be on the next episode? You can! All you need is the willingness to talk about something technical.

Music is by Joe Ferg, check out more music on JoeFerg.com!

This is a repost that originally appeared on the Couchbase Blog: Dependency Injection with ASP.NET Core and Couchbase.

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:

services.AddCouchbase(client =>
{
    client.Servers = new List<Uri> { new Uri("http://localhost:8091")};
    client.UseSsl = false;
});

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

services.AddCouchbase(Configuration.GetSection("Couchbase"));

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

"Couchbase" : {
  "Servers": [
    "http://localhost:8091"
  ],
  "UseSsl": false
}

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:

public class HomeController : Controller
{
    private readonly IBucket _bucket;

    public HomeController(IBucketProvider bucketProvider)
    {
        _bucket = bucketProvider.GetBucket("travel-sample", "password");
    }

    // ... snip ...
}

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.

public IActionResult About()
{
    // get the route document for Columbus to Chicago (United)
    var route = _bucket.Get<dynamic>("route_56027").Value;

    // display the equipment number of the route
    ViewData["Message"] = "CMH to ORD - " + route.equipment;

    return View();
}

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:

public interface ITravelSampleBucketProvider : INamedBucketProvider
{
    // nothing goes in here!
}

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

services
    .AddCouchbase(Configuration.GetSection("Couchbase"))
    .AddCouchbaseBucket<ITravelSampleBucketProvider>("travel-sample", "password");

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

public HomeController(ITravelSampleBucketProvider travelBucketProvider)
{
    _bucket = travelBucketProvider.GetBucket();
}

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.

public class ComplexService : IComplexService
{
    private readonly IBucket _bucket;
    private readonly IEmailService _email;

    public ComplexService(ITravelSampleBucketProvider bucketProvider, IEmailService emailService)
    {
        _bucket = bucketProvider.GetBucket();
        _email = emailService;
    }

    public void ApproveApplication(string emailAddress)
    {
        _bucket.Upsert(emailAddress, new {emailAddress, approved = true});
        _email.SendEmail(emailAddress, "Approved", "Your application has been approved!");
    }
}

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.

public class ApproveController : Controller
{
    private readonly IComplexService _svc;

    public ApproveController(IComplexService svc)
    {
        _svc = svc;
    }

    public IActionResult Index()
    {
        var fakeEmailAddress = Faker.Internet.Email();
        _svc.ApproveApplication(fakeEmailAddress);
        ViewData["Message"] = "Approved '" + fakeEmailAddress + "'";
        return View();
    }
}

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:

services.AddTransient<IEmailService, MyEmailService>();
services.AddTransient<IComplexService, ComplexService>();

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:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime)

Within that Configure method, setup an ApplicationStopped event:

applicationLifetime.ApplicationStopped.Register(() =>
{
    app.ApplicationServices.GetRequiredService<ICouchbaseLifetimeService>().Close();
});

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.

Ack, WebForms! Burn it with fire!

WebForms is known to be a horrible ghetto full of HTML pitfalls, a Kafka-esque lifecycle, testability nightmares, and pages served up with inflated ViewState data.

Some of that is still true, but WebForms has improved, and despite all the horrors that we're familiar with, it's still got a lot going for it, including a control tree that can be very useful at times.

I have been working on a WebForms project in my independent consulting practice (it sounds so fancy when I say it like that). Even though it's a relatively small project, I was still thinking about how best to introduce dependency inversion [PDF] to the project (or if I even should).

I googled around, sifted through a lot of ancient blog posts, and I came up with a relatively simple solution with my favorite IoC tool, StructureMap. It's not really optimal, or terribly elegant, but it just might get the job done and still allow us to write tests. I'm certainly open to alternatives, but because this is a small project, I don't want to spend a ton of billable hours on a solution, especially when I'll be turning the code over to novice programmer(s) when my time is done.

First, I simply add standard StructureMap config to the project. Application_Start in Global.asax is as good a place as any. I also use the default convention (if you aren't familiar, it's basically naming the interface by prepending an "I" to the concrete class name).

Okay, so that's pretty standard. Now let's approach from the other end: an actual code-behind class of an ASPX page. I can't use constructor injection here, because I don't have much control over this object being instantiated. Instead, I'll just make public properties for my service(s).

So now I've got a StructureMap defintion, and I've got properties that want to be set by StructureMap. But how do I get them talking? My solution was to introduce a base class (bleck) to the WebForms page. In this constructor, I'll use StructureMap's BuildUp method to populate properties (I have to specify which ones, as noted later on).

That's the ugliest part, as far as I'm concerned, but I couldn't think of a better solution. Maybe an HttpModule or something? Maybe the newer WebForms releases contain something that I'm not familar with yet? Leave a comment with your suggestions.

Finally, StructureMap just won't go and set every property by itself. You need to specify which ones. There are a couple of ways to do this. One is the SetAllProperties, which allows you to conditionally examine the PropertyInfo, and the other is FillAllPropertiesOfType, which you can use to directly specify which properties to set based on what type they are. Even though it's a small project, I'd would prefer to use SetAllProperties, so I don't have to go back and edit my StructureMap config each time I create a new service or a new WebForms page.

Matthew D. Groves

About the Author

Matthew D. Groves lives in Central Ohio. He works remotely, loves to code, and is a Microsoft MVP.

Latest Comments

Twitter