setupLocator function

Future<void> setupLocator()

Sets up the dependency injection locator with all application services.

This function initializes and registers all necessary services, repositories, view models, and providers in the correct dependency order. It should be called early in the application lifecycle, typically in main() before running the app.

The registration order is important:

  1. External packages (SharedPreferences, HTTP client, UUID)
  2. Core services (Database, PyTorch, User, Classification)
  3. Repositories (Data access layer)
  4. ViewModels (Business logic layer)
  5. Providers (State management)

All services are registered as lazy singletons to ensure proper initialization and memory management.

Throws:

  • Any exception that occurs during service initialization

Example:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await setupLocator();
  runApp(MyApp());
}

Implementation

Future<void> setupLocator() async {
  // External packages
  final prefs = await SharedPreferences.getInstance();
  locator.registerSingleton<SharedPreferences>(prefs);
  locator.registerLazySingleton(() => const Uuid());
  locator.registerLazySingleton(() => http.Client());

  // Services
  locator.registerLazySingleton(() => DatabaseService());
  locator.registerLazySingleton(() => PytorchWrapper());
  locator.registerLazySingleton(
      () => UserService(prefs: locator(), uuid: locator()));
  locator.registerLazySingleton(
      () => ClassificationService(pytorchWrapper: locator()));

  // Repositories
  locator.registerLazySingleton(
      () => MosquitoRepository(databaseService: locator()));
  locator.registerLazySingleton(() => ClassificationRepository(
      classificationService: locator(),
      mosquitoRepository: locator(),
      httpClient: locator()));

  // ViewModels
  locator.registerLazySingleton(() => ClassificationViewModel(
      repository: locator(), userService: locator()));
  locator.registerLazySingleton(
      () => DiseaseInfoViewModel(repository: locator()));
  locator.registerLazySingleton(
      () => MosquitoGalleryViewModel(repository: locator()));

  // Providers
  locator.registerLazySingleton(() => LocaleProvider(prefs: locator()));
}