Implementing the DI pattern via RepositoryProvider
The idea behind the DI pattern is that instead of creating or accessing dependencies internally, as we did in CartBloc
, the dependencies of the consumer class are passed and created during runtime. This decouples the creation of the dependency from its use. In our case, CartBloc
doesn’t need to know where the dependency comes from, as long as it satisfies the contract. The question then becomes the following: where and how should we inject the dependency?
Injecting dependencies via a constructor
One convenient way to ensure the satisfaction of dependencies is to pass them to the constructor. By doing so, it becomes impossible to create an instance of this object without providing the necessary dependencies. Furthermore, this responsibility is delegated to the instantiating class, relieving the consumer class of this burden. Therefore, implementing this in CartBloc
would look like the following code blocks.
Here is what...