13 The Autofac DI Container

 

In this chapter

  • Working with Autofac’s basic registration API
  • Managing component lifetime
  • Configuring difficult APIs
  • Configuring sequences, Decorators, and Composites

In the previous chapters, we discussed patterns and principles that apply to DI in general, but, apart from a few examples, we’ve yet to take a detailed look at how to apply them using any particular DI Container. In this chapter, you’ll see how these overall patterns map to Autofac. You’ll need to be familiar with the material from the previous chapters to fully benefit from this.

Autofac is a fairly comprehensive DI Container that offers a carefully designed and consistent API. It’s been around since late 2007 and is, at the time of writing, one of the most popular containers.1

In this chapter, we’ll examine how Autofac can be used to apply the principles and patterns presented in parts 1–3. This chapter is divided into four sections. You can read each section independently, though the first section is a prerequisite for the other sections, and the fourth section relies on some methods and classes introduced in the third section.

13.1 Introducing Autofac

13.1.1 Resolving objects

13.1.2 Configuring the ContainerBuilder

13.2 Managing lifetime

13.2.1 Configuring instance scopes

13.2.2 Releasing components

13.3 Registering difficult APIs

13.3.1 Configuring primitive Dependencies

13.3.2 Registering objects with code blocks

13.4 Working with multiple components

13.4.1 Selecting among multiple candidates

13.4.2 Wiring sequences

13.4.3 Wiring Decorators

13.4.4 Wiring Composites

Summary