-
Notifications
You must be signed in to change notification settings - Fork 3
/
ioc_container.dart
338 lines (289 loc) · 10.4 KB
/
ioc_container.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import 'dart:async';
import 'package:ioc_container/async_lock.dart';
///❌ An exception that occurs when the service is not found
class ServiceNotFoundException<T> implements Exception {
///❌ Creates a new instance of [ServiceNotFoundException]
const ServiceNotFoundException(this.message);
///The exception message
final String message;
@override
String toString() => 'ServiceNotFoundException: $message';
}
///📙 Defines a factory for the service and whether or not it is a singleton.
class ServiceDefinition<T> {
///📙 Defines a factory for the service and whether or not it is a singleton.
const ServiceDefinition(
this.factory, {
this.isSingleton = false,
this.dispose,
this.disposeAsync,
}) : assert(
dispose == null || disposeAsync == null,
"Service definitions can't have both dispose and disposeAsync",
);
///1️⃣ If true, only one instance of the service will be created and shared
///for the lifespan of the container.
final bool isSingleton;
///🏭 The factory that creates the instance of the service and can access
///other services in this container
final T Function(
IocContainer container,
) factory;
///🗑️ The dispose method that is called when you dispose the scope
final void Function(T service)? dispose;
///🗑️ The async dispose method that is called when you dispose the scope
final Future<void> Function(T service)? disposeAsync;
void _dispose(T instance) => dispose?.call(instance);
Future<void> _disposeAsync(T instance) async => disposeAsync?.call(instance);
}
///📦 A built Ioc Container. To create a new [IocContainer], use
///[IocContainerBuilder]. To get a service from the container, call
///[get], or [getAsync]
///Call [scoped] to get a scoped container
class IocContainer {
///📦 Creates an IocContainer. You can build your own container by injecting
///service definitions and singletons here, but you should probably use
///[IocContainerBuilder] instead.
const IocContainer(
this.serviceDefinitionsByType,
this.singletons,
this.locks, {
this.isScoped = false,
});
///📙 The service definitions by type
final Map<Type, ServiceDefinition<dynamic>> serviceDefinitionsByType;
///1️⃣ Map of singletons or scoped services by type. This map is mutable
///so the container can store scope or singletons
final Map<Type, Object> singletons;
///🔒 Map of locks by type. This ensures that no async singletons execute
///more than once, unless there is an error
// ignore: strict_raw_type
final Map<Type, AsyncLock> locks;
///⌖ If true, this container is a scoped container. Scoped containers never
///create more than one instance of a service
final bool isScoped;
///👐 Get an instance of the service by type
T get<T extends Object>() {
final serviceDefinition = serviceDefinitionsByType[T];
if (serviceDefinition == null) {
throw ServiceNotFoundException<T>(
'Service $T not found',
);
}
if (serviceDefinition.isSingleton || isScoped) {
final singletonValue = singletons[T];
if (singletonValue != null) {
return singletonValue as T;
}
}
final service = serviceDefinition.factory(this) as T;
if (serviceDefinition.isSingleton || isScoped) {
singletons[T] = service;
}
return service;
}
///👐 This is a shortcut for [get]
T call<T extends Object>() => get<T>();
}
///👷 A builder for creating an [IocContainer].
class IocContainerBuilder {
///👷 Creates a container builder
IocContainerBuilder({this.allowOverrides = false});
final Map<Type, ServiceDefinition<dynamic>> _serviceDefinitionsByType = {};
/// 🔃 Throw an error if a service is added more than once. Set this to true
/// when you want to add mocks to set of services for a test.
final bool allowOverrides;
///📙 Add a factory to the container.
void addServiceDefinition<T>(
///Add a factory and whether or not this service is a singleton
ServiceDefinition<T> serviceDefinition,
) {
if (_serviceDefinitionsByType.containsKey(T)) {
if (allowOverrides) {
_serviceDefinitionsByType.remove(T);
} else {
throw Exception('Service already exists');
}
}
_serviceDefinitionsByType.putIfAbsent(T, () => serviceDefinition);
}
///📦 Create an [IocContainer] from the [IocContainerBuilder].
IocContainer toContainer() => IocContainer(
Map<Type, ServiceDefinition<dynamic>>.unmodifiable(
_serviceDefinitionsByType,
),
<Type, Object>{},
// ignore: strict_raw_type
<Type, AsyncLock>{},
);
///1️⃣ Add a singleton factory to the container. The container
///will only call this once throughout the lifespan of the container
void addSingleton<T>(
T Function(
IocContainer container,
) factory, {
void Function(T service)? dispose,
}) =>
addServiceDefinition<T>(
ServiceDefinition<T>(
(container) => factory(container),
isSingleton: true,
dispose: dispose,
),
);
///🏭 Add a factory to the container.
void add<T>(
T Function(
IocContainer container,
) factory, {
void Function(T service)? dispose,
}) =>
addServiceDefinition<T>(
ServiceDefinition<T>(
(container) => factory(container),
dispose: dispose,
),
);
///⌛ Adds an async [ServiceDefinition]
void addAsync<T>(
Future<T> Function(
IocContainer container,
) factory, {
Future<void> Function(T service)? disposeAsync,
}) =>
addServiceDefinition<Future<T>>(
ServiceDefinition<Future<T>>(
(container) async => factory(container),
disposeAsync: (service) async => disposeAsync?.call(await service),
),
);
///1️⃣ ⌛ Add an async singleton factory to the container. The container
///will only call the factory once throughout the lifespan of the container
void addSingletonAsync<T>(
Future<T> Function(
IocContainer container,
) factory, {
Future<void> Function(T service)? disposeAsync,
}) =>
addServiceDefinition<Future<T>>(
ServiceDefinition<Future<T>>(
isSingleton: true,
(container) async => factory(container),
disposeAsync: (service) async => disposeAsync?.call(await service),
),
);
}
///Extensions for IocContainer
extension IocContainerExtensions on IocContainer {
///🗑️ Dispose all singletons or scope. Warning: don't use this on your root
///container. You should only use this on scoped containers.
Future<void> dispose() async {
assert(isScoped, 'Only dispose scoped containers');
for (final type in singletons.keys) {
//Note: we don't need to check if the service is a singleton because
//singleton service definitions never have dispose
final serviceDefinition = serviceDefinitionsByType[type]!;
//We can't do a null check here because if a Dart issue
serviceDefinition._dispose.call(singletons[type]);
await serviceDefinition._disposeAsync(singletons[type]);
}
singletons.clear();
}
///🏁 Initalizes and stores each singleton in case you want a zealous
///container instead of a lazy one
void initializeSingletons() {
serviceDefinitionsByType.forEach((type, serviceDefinition) {
if (serviceDefinition.isSingleton) {
singletons.putIfAbsent(
type,
() => serviceDefinition.factory(
this,
) as Object,
);
}
});
}
///⌖ Gets a service, but each service in the object mesh will have only one
///instance. If you want to get multiple scoped objects, call [scoped] to
///get a reusable [IocContainer] and then call [get] or [getAsync] on that.
T getScoped<T extends Object>() => scoped().get<T>();
///⌖ Creates a new Ioc Container for a particular scope. Does not use existing
///singletons/scope by default. Warning: if you use the existing singletons,
///calling [dispose] will dispose those singletons
IocContainer scoped({
bool useExistingSingletons = false,
}) =>
IocContainer(
serviceDefinitionsByType,
useExistingSingletons ? Map<Type, Object>.from(singletons) : {},
{},
isScoped: true,
);
///⌛ Gets a service that requires async initialization. Add these services
///with [IocContainerBuilder.addAsync] or
///[IocContainerBuilder.addSingletonAsync]. You can only use this on factories
///that return a Future<>.
Future<T> getAsync<T>([
Duration? timeout = const Duration(minutes: 5),
]) async {
final serviceDefinition = serviceDefinitionsByType[Future<T>];
if (serviceDefinition == null) {
throw ServiceNotFoundException<T>(
'Service $T not found',
);
}
if (serviceDefinition.isSingleton || isScoped) {
final singletonValue = singletons[Future<T>];
if (singletonValue != null) {
//Return completed successful future
return singletonValue as Future<T>;
}
if (!locks.containsKey(T)) {
//Add a lock
locks[T] =
AsyncLock<T>(() => serviceDefinition.factory(this) as Future<T>);
}
final lock = locks[T]! as AsyncLock<T>;
try {
//Await the locked call
final future = timeout != null ? lock.execute(timeout) : lock.execute();
await future;
//Store successful future
singletons[Future<T>] = future;
return future;
} finally {
//Remove the lock
locks.remove(T);
}
}
return serviceDefinition.factory(this) as Future<T>;
}
///⛙ Merge the singletons or scope from a container into this container. This
///only moves singleton definitions by default, but you can override this
///with [mergeTest]
void merge(
IocContainer container, {
bool overwrite = false,
bool Function(
Type type,
ServiceDefinition<dynamic>? serviceDefinition,
Object? singleton,
)? mergeTest,
}) {
for (final key in container.singletons.keys.where(
mergeTest != null
? (type) => mergeTest(
type,
serviceDefinitionsByType[type],
container.singletons[type],
)
: (type) => serviceDefinitionsByType[type]?.isSingleton ?? false,
)) {
if (overwrite) {
singletons[key] = container.singletons[key]!;
} else {
singletons.putIfAbsent(key, () => container.singletons[key]!);
}
}
}
}