Appearance
💉 Dependency Injection
Overview
Dependency Injection (DI) is a design pattern that promotes loose coupling and testability by providing dependencies to a class from external sources rather than having the class create them itself.
General Principles
- Inversion of Control (IoC): DI is a form of IoC, where the control of object creation and dependency management is inverted to a separate container or factory.
- Loose Coupling: DI reduces the dependencies between classes, making the code more modular and easier to maintain.
- Testability: DI makes it easier to test classes in isolation by allowing dependencies to be mocked or stubbed.
- Reusability: DI promotes code reuse by allowing components to be easily swapped and configured.
Guidelines
- Use
get_itpackage as the DI container. - Register dependencies as singletons, lazy singletons, or factories based on their lifecycle requirements.
- Use
getIt.registerSingletonfor dependencies that should only be created once. - Use
getIt.registerLazySingletonfor dependencies that should be created only when they are first needed. - Use
getIt.registerFactoryfor dependencies that should be created every time they are requested. - Use
getIt.registerFactoryParamfor dependencies that require parameters to be created.
Code Standards for app_di.dart
- The
app_di.dartfile should be responsible for configuring and initializing the DI container. - The
setup()method should be used to register all dependencies. - The
setup()method should be called early in the application lifecycle, before any dependencies are needed. - Use clear and descriptive names for registered dependencies.
- Group related dependencies together for better organization.
- Avoid registering dependencies that are not used in the application.
- Use the
getItinstance to retrieve dependencies throughout the application. - Make sure to register all the
cubits,repos,services.