-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.dart
More file actions
288 lines (236 loc) · 12.5 KB
/
example.dart
File metadata and controls
288 lines (236 loc) · 12.5 KB
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
// ignore_for_file: avoid_print
import 'package:davianspace_configuration/davianspace_configuration.dart';
import 'package:davianspace_dependencyinjection/davianspace_dependencyinjection.dart';
import 'package:davianspace_options/davianspace_options.dart';
// ─────────────────────────────────────────────────────────────────────────────
// Options & Configuration models (for examples 9 & 10)
// ─────────────────────────────────────────────────────────────────────────────
class ServerOptions {
String host = 'localhost';
int port = 8080;
bool useSsl = false;
}
// ─────────────────────────────────────────────────────────────────────────────
// Domain abstractions
// ─────────────────────────────────────────────────────────────────────────────
abstract class ILogger {
void log(String message);
}
abstract class IDatabase {
Future<String> query(String sql);
}
abstract class IUserRepository {
Future<String> findById(int id);
}
abstract class ICacheService {
String? get(String key);
void set(String key, String value);
}
// ─────────────────────────────────────────────────────────────────────────────
// Implementations
// ─────────────────────────────────────────────────────────────────────────────
class ConsoleLogger implements ILogger {
@override
void log(String message) => print('[LOG] $message');
}
class PostgresDatabase implements IDatabase {
final ILogger _logger;
PostgresDatabase(this._logger);
@override
Future<String> query(String sql) async {
_logger.log('Query: $sql');
await Future<void>.delayed(const Duration(milliseconds: 5));
return 'pg_result[$sql]';
}
}
class UserRepository implements IUserRepository {
final IDatabase _db;
UserRepository(this._db);
@override
Future<String> findById(int id) =>
_db.query('SELECT * FROM users WHERE id = $id');
}
class MemoryCacheService implements ICacheService {
final _store = <String, String>{};
@override
String? get(String key) => _store[key];
@override
void set(String key, String value) => _store[key] = value;
}
class RedisCacheService implements ICacheService {
final _store = <String, String>{};
@override
String? get(String key) => _store[key];
@override
void set(String key, String value) => _store[key] = value;
}
// ─────────────────────────────────────────────────────────────────────────────
// Register constructor factories with ReflectionHelper
// (required because Dart has no runtime reflection in AOT)
// ─────────────────────────────────────────────────────────────────────────────
void _registerFactories() {
ReflectionHelper.instance
..register(ConsoleLogger, (_) => ConsoleLogger())
..register(
PostgresDatabase,
(resolve) => PostgresDatabase(resolve(ILogger) as ILogger),
)
..register(
UserRepository,
(resolve) => UserRepository(resolve(IDatabase) as IDatabase),
)
..register(MemoryCacheService, (_) => MemoryCacheService())
..register(RedisCacheService, (_) => RedisCacheService());
}
// ─────────────────────────────────────────────────────────────────────────────
// Main
// ─────────────────────────────────────────────────────────────────────────────
Future<void> main() async {
_registerFactories();
// ── 1. Build the container ────────────────────────────────────────────────
final sc = ServiceCollection()
// Singleton: one ConsoleLogger for the whole app.
..addSingleton<ILogger, ConsoleLogger>()
// Singleton: one PostgresDatabase — async factory.
..addSingletonAsync<IDatabase>((p) async {
final logger = p.getRequired<ILogger>();
logger.log('Initialising database connection…');
await Future<void>.delayed(const Duration(milliseconds: 10));
return PostgresDatabase(logger);
})
// Scoped: fresh UserRepository per HTTP request / scope.
..addScoped<IUserRepository, UserRepository>()
// Keyed Singleton: two named cache implementations.
..addKeyedSingletonFactory<ICacheService>(
'memory',
(p, k) => MemoryCacheService(),
)
..addKeyedSingletonFactory<ICacheService>(
'redis',
(p, k) => RedisCacheService(),
);
final provider = sc.buildServiceProvider(
const ServiceProviderOptions(
validateOnBuild: true,
validateScopes: true,
enableDiagnostics: true,
),
);
// ── 2. Subscribe to diagnostics ───────────────────────────────────────────
// (Must subscribe before resolving when enableDiagnostics is true.)
print('\n=== davianspace_dependencyinjection example ===\n');
print(provider.dumpRegistrations());
// ── 3. Async singleton resolution ────────────────────────────────────────
final db = await provider.getAsync<IDatabase>();
final result = await db.query('SELECT 1');
print('DB result: $result');
// ── 4. Scoped resolution ─────────────────────────────────────────────────
final scope1 = provider.createScope();
final repo1 = scope1.serviceProvider.getRequired<IUserRepository>();
print(await repo1.findById(1));
final scope2 = provider.createScope();
final repo2 = scope2.serviceProvider.getRequired<IUserRepository>();
print(await repo2.findById(2));
// Scoped services are isolated per scope — different instances across scopes.
print(
'repo1 is repo2? ${identical(repo1, repo2)}'); // false — scoped isolation confirmed
scope1.dispose();
scope2.dispose();
// ── 5. Keyed services ────────────────────────────────────────────────────
final memCache = provider.getRequiredKeyed<ICacheService>('memory');
final redisCache = provider.getRequiredKeyed<ICacheService>('redis');
memCache.set('user:1', 'Alice');
redisCache.set('session:abc', 'active');
print('MemCache user:1 → ${memCache.get('user:1')}');
print('RedisCache session:abc → ${redisCache.get('session:abc')}');
// ── 6. isRegistered / tryGetAsync ────────────────────────────────────────
print('\nisRegistered<ILogger>: ${provider.isRegistered<ILogger>()}');
print('isRegistered<String>: ${provider.isRegistered<String>()}');
final maybeLogger = await provider.tryGetAsync<ILogger>();
print('tryGetAsync<ILogger>: ${maybeLogger != null ? 'resolved' : 'null'}');
final nothing = await provider.tryGetAsync<String>();
print('tryGetAsync<String> (unregistered): $nothing');
// ── 7. getAll — consume all registered implementations of a service ────────
// Register two named cache implementations under the same abstract type,
// then resolve all of them in one call — useful for broadcast patterns
// (e.g. fan-out notifications, composite health checks).
final multiSc = ServiceCollection()
..addSingleton<ICacheService, MemoryCacheService>()
..addSingleton<ICacheService, RedisCacheService>();
final multiProvider = multiSc.buildServiceProvider();
final allCaches = multiProvider.getAll<ICacheService>();
print('\ngetAll<ICacheService> resolved ${allCaches.length} implementations');
await multiProvider.disposeAsync();
// ── 8. replace — swap an implementation without rebuilding the collection ──
// Useful during testing or when environment-specific overrides are applied
// after the initial service registration pass.
final overrideSc = ServiceCollection()
..addSingleton<ILogger, ConsoleLogger>()
..replace(ServiceDescriptor.factoryFn(
serviceType: ILogger,
lifetime: ServiceLifetime.singleton,
factory: (_) => ConsoleLogger(), // swap to a different concrete type
));
final overrideProvider = overrideSc.buildServiceProvider();
final overriddenLogger = overrideProvider.getRequired<ILogger>();
overriddenLogger.log('Resolved from overridden registration');
await overrideProvider.disposeAsync();
// ── 9. Options Pattern ──────────────────────────────────────────────────────
// configure<T> registers Options<T> (singleton), OptionsSnapshot<T>
// (scoped), and OptionsMonitor<T> (singleton) automatically.
final optionsSc = ServiceCollection()
..configure<ServerOptions>(
factory: ServerOptions.new,
configure: (opts) {
opts.host = 'api.prod.internal';
opts.port = 443;
opts.useSsl = true;
},
);
final optionsProvider =
optionsSc.buildServiceProvider(ServiceProviderOptions.production);
final singletonOpts =
optionsProvider.getRequired<Options<ServerOptions>>().value;
print('\n[Options] host=${singletonOpts.host} port=${singletonOpts.port}'
' ssl=${singletonOpts.useSsl}');
// OptionsMonitor supports live reload via keyed OptionsChangeNotifier.
var reloadCount = 0;
final monitor = optionsProvider.getRequired<OptionsMonitor<ServerOptions>>();
final reg = monitor.onChange((opts, _) {
reloadCount++;
print('[Options] reloaded: host=${opts.host}');
});
final notifier =
optionsProvider.getRequiredKeyed<OptionsChangeNotifier>(ServerOptions);
notifier.notifyChange(Options.defaultName); // triggers the listener above
print('[Options] reload count: $reloadCount');
reg.dispose();
optionsProvider.dispose();
// ── 10. Configuration ───────────────────────────────────────────────
// addConfiguration registers Configuration (and ConfigurationRoot)
// as injectable singletons. Options can be bound directly from config.
final config = ConfigurationBuilder().addMap({
'server': {'host': 'config.prod.internal', 'port': 443, 'useSsl': true},
}).build();
final configSc = ServiceCollection()
..addConfiguration(config)
..configure<ServerOptions>(
factory: ServerOptions.new,
configure: (opts) {
final s = config.getSection('server');
opts.host = s['host'] ?? 'localhost';
opts.port = int.parse(s['port'] ?? '8080');
opts.useSsl = (s['useSsl'] ?? 'false') == 'true';
},
);
final configProvider =
configSc.buildServiceProvider(ServiceProviderOptions.production);
final cfg = configProvider.getRequired<Configuration>();
print('\n[Configuration] server:host=${cfg['server:host']}');
final cfgOpts =
configProvider.getRequired<Options<ServerOptions>>().value;
print('[Configuration+Options] host=${cfgOpts.host} ssl=${cfgOpts.useSsl}');
configProvider.dispose();
// ── 11. Dispose the root provider ─────────────────────────────────────────
await provider.disposeAsync();
}