Dependency injection
A part of a program should ask for what it needs and not create it. A service container makes the objects and decides how long each one lives. This lesson uses the container of .NET with its three lifetimes — singleton, transient and scoped — and a service that needs another service.
What you will learn#
- what dependency injection (DI) is and why programs use it,
ServiceCollectionand the service provider,- the three lifetimes: singleton, transient, scoped,
- scopes (
CreateScope) and what one request means, - factories that ask the provider for other services,
- the rules that avoid mistakes.
Every ASP.NET Core program is built on this container, so what you learn here is what a web program (the tutorial A web service with a database) is using inside.
The program#
# dependency injection - a service container, the three lifetimes (singleton, transient, scoped) and services that need other services
load "dotnet.ring"
using {
"System"
"System.Collections"
"System.IO"
"Microsoft.Extensions.DependencyInjection"
}
nSingletons = 0
nTransients = 0
nScoped = 0
func main
# Dependency injection (DI) means: a part of a program does not create the things it needs, it ASKS for them. A container makes them,
# and decides how long each one lives. That makes the parts easy to replace and to test, and it is how every ASP.NET program is built.
# The container works with .NET types as the keys. Here three plain types stand for three services, and a Ring function makes each one
# (the "factory"): ArrayList = a long-lived service, Random = a new one each time, MemoryStream = one for each request.
oServices = new ServiceCollection
oServices.AddSingleton([ :serviceType = dnType("System.Collections.ArrayList"), :implementationFactory = dnCallback("makeSingleton") ])
oServices.AddTransient([ :serviceType = dnType("System.Random"), :implementationFactory = dnCallback("makeTransient") ])
oServices.AddScoped([ :serviceType = dnType("System.IO.MemoryStream"), :implementationFactory = dnCallback("makeScoped") ])
oProvider = oServices.BuildServiceProvider(NULL)
? "1. " + oServices.Count + " services are registered; the provider is built"
# 2. SINGLETON: one object for the whole program. It is made the first time somebody asks.
oArrayList = dnType("System.Collections.ArrayList")
oFirst = oProvider.GetService(oArrayList)
oSecond = oProvider.GetService(oArrayList)
? nl + "2. singleton: asked twice, made " + nSingletons + " time(s), the same object: " + oFirst.Equals(oSecond)
# 3. TRANSIENT: a new object every time. Good for light things that must not share state.
oRandom = dnType("System.Random")
oOne = oProvider.GetService(oRandom)
oTwo = oProvider.GetService(oRandom)
? nl + "3. transient: asked twice, made " + nTransients + " time(s), the same object: " + oOne.Equals(oTwo)
# 4. SCOPED: one object for each SCOPE. A scope is one unit of work: in a web server, one request. Inside a scope the same object comes
# back; another scope gets its own.
oStream = dnType("System.IO.MemoryStream")
oScope1 = oProvider.CreateScope()
oScope2 = oProvider.CreateScope()
oServices1 = oScope1.ServiceProvider
oServices2 = oScope2.ServiceProvider
oInScope1a = oServices1.GetService(oStream)
oInScope1b = oServices1.GetService(oStream)
oInScope2 = oServices2.GetService(oStream)
? nl + "4. scoped: made " + nScoped + " time(s) for 2 scopes"
? " twice in the same scope, the same object: " + oInScope1a.Equals(oInScope1b)
? " in another scope, the same object: " + oInScope1a.Equals(oInScope2)
# 5. The factory receives the provider, so a service can ask for the services it needs: the scoped MemoryStream asks for the singleton
# ArrayList and writes its name in it. Every scope reaches the SAME list: that is how a singleton shares data.
? nl + "5. the singleton list now says: " + oFirst.Count + " entries, from the " + oFirst.Item(0) + " and the " + oFirst.Item(1)
oScope1.Dispose()
oScope2.Dispose()
# 6. The rules of thumb. A service must not keep a shorter-lived service inside it (a singleton that holds a scoped object would keep it
# for ever, and share it between requests). Things that hold a file, a connection or a lot of memory are disposed when their scope ends.
? nl + "6. total made: singleton " + nSingletons + ", transient " + nTransients + ", scoped " + nScoped
func makeSingleton aArguments
nSingletons++
return new ArrayList
func makeTransient aArguments
nTransients++
return new Random
# the first value of the arguments is the provider of the scope: it can give other services
func makeScoped aArguments
nScoped++
oProvider = aArguments[1]
oList = oProvider.GetService(dnType("System.Collections.ArrayList"))
if nScoped = 1
oList.Add("first scope")
else
oList.Add("second scope")
ok
return new MemoryStream1. 3 services are registered; the provider is built
2. singleton: asked twice, made 1 time(s), the same object: 1
3. transient: asked twice, made 2 time(s), the same object: 0
4. scoped: made 2 time(s) for 2 scopes
twice in the same scope, the same object: 1
in another scope, the same object: 0
5. the singleton list now says: 2 entries, from the first scope and the second scope
6. total made: singleton 1, transient 2, scoped 2This program uses a few generic functions (dnType, callMethod) where a class cannot be used. The lesson The generic functions explains them.
How it works#
The idea#
Without DI, a function that sends mail creates its own mail client, and a test of that function sends real mail. With DI, the function asks the container for a mail client; the program registers the real one, and a test registers a fake one. The code that uses a service does not know how it is made, and the code that makes it does not know who uses it.
The container is a ServiceCollection (the list of registrations); BuildServiceProvider turns it into a provider that makes the objects. A service is asked for with its type: oProvider.GetService(type). The keys are .NET types, so in this lesson three ordinary types stand for three services: ArrayList, Random and MemoryStream. Ring classes cannot be registered (they are not .NET types), but a Ring function can be the factory that makes the object: AddSingleton(serviceType, factory) with dnCallback("makeSingleton"). AddSingleton, AddTransient, AddScoped and BuildServiceProvider are extension methods that the class ServiceCollection has as methods (the tutorial Caching). Each of them has several forms, so the names of the parameters choose one: oServices.AddSingleton([ :serviceType = dnType("System.Collections.ArrayList"), :implementationFactory = dnCallback("makeSingleton") ]), and BuildServiceProvider(NULL) is the form without parameters.
Singleton#
One object for the whole program, made the first time somebody asks. Asked twice, the factory ran once and both answers are the same object (Equals of these types compares the object itself). Use it for things that are expensive to make or must be shared: a cache (the tutorial Caching), a configuration (the tutorial Configuration), a logger. A singleton must be safe for use by many threads at once.
Transient#
A new object every time. Asked twice, the factory ran twice and the objects are different. Use it for light things that must not share state.
Scoped#
One object for each scope. A scope is one unit of work: in a web server, one request. CreateScope makes one; the objects asked for through the scope are the same inside it and different in another scope. In the output the factory ran twice for two scopes, the same scope gives the same object and another scope gives another. When the scope is disposed, the scoped objects that need it are disposed too (files, connections). CreateScope is an extension method and the scope's provider has the method GetService: keep it in a variable (oServices = oScope.ServiceProvider) and call oServices.GetService(type).
Services that need services#
A factory receives the provider as its first value, so it can ask for what it needs. The scoped MemoryStream of the program asks for the singleton ArrayList and writes the name of its scope in it; both scopes reach the same list, which then holds two entries. This is how a singleton shares data between requests — and why it must be safe for that.
Rules of thumb#
- A long-lived service must not hold a shorter-lived one. A singleton that keeps a scoped object keeps it for ever and shares it between requests ("captive dependency"); .NET can check this when the provider is built in development mode.
- Make the simplest lifetime that works: transient for light, stateless things, scoped for what belongs to one request, singleton only for what must be shared.
- Ask for services in one place (the start of the program or the request), and pass them down as values, instead of asking the container everywhere (that is the service locator style, which hides what a function needs).
What you learned#
- DI: a part asks for what it needs, a container makes it,
ServiceCollection,BuildServiceProvider,GetService,- singleton, transient and scoped lifetimes and scopes,
- Ring functions as factories,
- a factory can ask the provider for other services,
- the captive dependency mistake.
Exercises#
- Register a fourth service and print how many times its factory ran for 10 requests (10 scopes).
- Make a scope, get a scoped
MemoryStreamfrom it, write to it and dispose the scope. - Register the same type twice and see which one
GetServicereturns (the last one). - Look up
GetServices(many) andGetRequiredService(an error when missing) in the class reference.
Where to go next#
This was the last tutorial of the chapter Databases and services. The next chapter is Windows Forms: it starts with Your first window. The Tutorials page lists all the chapters, and you can start any of them.