You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/docs/basics/dependency-injection.md
+131-4Lines changed: 131 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,19 +4,21 @@ sidebar_position: 3
4
4
5
5
# Dependency Injection 💉
6
6
7
-
Middleware can also be used to provide dependencies to a `RequestContext` via a `provider`.
7
+
Middleware can be used to inject dependencies into a `RequestContext` via a `provider`.
8
+
9
+
## Provider
8
10
9
11
`provider` is a type of middleware that can create and provide an instance of type `T` to the request context. The `create` callback is called lazily and the injected `RequestContext` can be used to perform additional lookups to access values provided upstream.
10
12
13
+
### Basics
14
+
11
15
In the following example, we'll use a `provider` to inject a `String` into our request context.
12
16
13
17
```dart
14
18
import 'package:dart_frog/dart_frog.dart';
15
19
16
20
Handler middleware(Handler handler) {
17
-
return handler
18
-
.use(requestLogger())
19
-
.use(provider<String>((context) => 'Welcome to Dart Frog!'));
21
+
return handler.use(provider<String>((context) => 'Welcome to Dart Frog!'));
In the above example, we defined the `provider` inline. This is fine for simple cases, but for more complex providers or providers which you want to reuse, it can be helpful to extract the provider to its own file:
By default, a provided value will be created when it is accessed. This means that each time you read a value via `context.read`, the associated `create` method will be invoked.
134
+
135
+
As a result, you may wish to cache a provided value so that it isn't unnecessarily recreated on each read. We can do this quite easily by defining a provide value which we use to reference the provided value once it is created.
With the above implementations, the greeting will only be computed once and the cached value will be used for the duration of the application lifecycle.
0 commit comments