Search code examples
flutterdartdependency-injectiondependency-inversion

How is a method getting is called by an instance of its abstract class. I've attached the github issue


How is the method being called since the NumberTriviaRepository that is imported is just an abstract class whose implementation is in a completely different file as in the attached issue

Please refer: https://github.com/arc-arnob/clean_code_architecture_tdd_bloc/issues/15


Solution

  • This is a very interesting question. The connection between the abstract class and the concrete implementation is made by dependency injection. Let me give you a brief explanation of my understanding of this code flow. I hope it will clear up your confusion. If you look at the injection_container.dart file, you will see that NumberTriviaRepository is registered there and injected with the implementation.

    injection_container.dart

      //! Repository
      sl.registerLazySingleton<NumberTriviaRepository>(
        () => NumberTriviaRepositoryImplementation(
          localDataSource: sl(),
          networkInfo: sl(),
          remoteDataSource: sl(),
        ),
      );
    

    So when the GetConcreteNumberTrivia use case is invoked as it is also registered in injection_container.dart as a singleton, it creates a new instance if it doesn't exist or provides a previous instance.

    While creating that instance, it notices that it needs to inject NumberTriviaRepository. As it is also registered in injection_container.dart, it returns NumberTriviaRepositoryImplementation according to the instruction.

    That's how we can use the repository.getConcreteNumberTrivia(params.number) function, and the repository we are receiving in the constructor of the GetConcreteNumberTrivia class is the instance that we created in the injection file. I hope it helps you to understand this topic.