skipnothing/.NET Platform

The .NET DI Container

Wiring `new OrderService(new SmtpEmailSender(new SmtpConfig(...)))` by hand at every call site is the chore .NET will take over. Write down which concrete class fills which request, ask for the top of the graph, and the whole wired object comes back.

  • AddSingleton builds nothing: it appends a row mapping a request to a class, and nothing is constructed until you ask.
  • Ask for the top object once and every constructor in the tree is read and built bottom-up, no extra calls.
  • Forget a row and one resolve method throws, naming the missing class; the other just returns null.
BUILDS ON
01

Register Into a List

AddSingleton reads like it wires up a service. It mostly fills out a form.

var services = new ServiceCollection();

services.AddSingleton<IEmailSender, SmtpEmailSender>();
services.AddSingleton<IOrderRepository, SqlOrderRepository>();

Each call appends one entry to the IServiceCollection, a collection whose every item is a ServiceDescriptor. A descriptor writes down three fields: the service type you will later ask for (IEmailSender), the implementation type that satisfies it (SmtpEmailSender), and a lifetime (the third field, owned by the next topic). That is all registration is, a record of which concrete type fills which request. No SmtpEmailSender has been constructed, no constructor has run. The list is just data: a short stack of three-field rows. The machine that will read those rows and hand back real objects is the container, and so far you have only filled in its order form.

THE REGISTRATION LIST

Keep going, sign up to unlock the rest

3 more parts in this topic, plus 25+ more topics in .NET Platform.

Sign up, it's freeSee the full .NET Platform
Dependency Injection0/6#12 Why Dependency Injection
#14 Service Lifetimes