Dependency Injection
Zuraffa provides an automated, modular dependency injection setup using GetIt. By using the --di flag, Zuraffa generates and maintains registration files for your repositories, data sources, and services.
π¦ Architectureβ
Zuraffa's DI follows a "Lazy Singleton" approach by default, ensuring components are only instantiated when needed. The structure is split into domain-specific registration files to prevent circular dependencies and merge conflicts.
lib/src/di/
βββ datasources/
β βββ product_remote_datasource_di.dart
β βββ product_local_datasource_di.dart
βββ repositories/
β βββ product_repository_di.dart
βββ index.dart # Root registration entry point
βββ service_locator.dart # The GetIt instance
π Basic Usageβ
1. Generate with DIβ
When generating a feature, include the --di flag:
zfa feature Product --data --di
2. Initialize in main.dartβ
Import the generated index.dart and call setupDependencies() before runApp():
import 'package:get_it/get_it.dart';
import 'src/di/index.dart';
final getIt = GetIt.instance;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Register all Zuraffa dependencies
await setupDependencies(getIt);
runApp(MyApp());
}
π§ͺ Development with Mocksβ
Zuraffa makes it easy to swap real implementations for mocks during development or testing.
Swapping at Registrationβ
Use the --use-mock flag to register a MockDataSource instead of the RemoteDataSource:
zfa feature Product --data --mock --di --use-mock
Manual Swappingβ
You can also conditionally register dependencies based on your environment:
Future<void> setupDependencies(GetIt getIt) async {
if (kDebugMode) {
await registerProductMockDataSource(getIt);
} else {
await registerProductRemoteDataSource(getIt);
}
await registerProductRepository(getIt);
}
π§ Smart Registrationβ
Zuraffa's DI generator is "smart"βit understands your architectural choices:
- Caching: If
--cacheis used, the DI registration will automatically wire theRemoteDataSource,LocalDataSource, andCachePolicyinto theCachedRepository. - Services: If you use the
--servicepattern, Zuraffa generates a separate registration for the service interface and its implementation. - Custom View Preservation: Presentation layer components (View, Presenter, Controller) are not registered in the global DI container. Instead, they are instantiated within the View's state to ensure proper lifecycle management and cleanup.
π Next Stepsβ
- Caching - Dual datasource caching setup.
- Mock Data - Development with mock data.
- CLI Reference - Complete DI flag documentation.