Can anyone help me with using dependency injection on singleton?
here is my code:
class SpaceController extends ChangeNotifier {
final SpacesPersistence _persistence;
static final SpaceController _instance = SpaceController._internal(persistence: null);
factory SpaceController({required SpacesPersistence persistence}) {
return _instance;
}
SpaceController._internal({required SpacesPersistence persistence}) : _persistence = persistence;
}
abstract class SpacesPersistence {
Future<List<Entry>> getPath();
Future<List<Entry>> getEntries(Entry? parent, [String? keyword]);
Future<List<Connection>> getConnections([List<Entry>? entries]);
Future<void> add(Entry entry);
Future<void> remove(Entry entry);
Future<void> update(Entry entry);
Future<void> setPath(List<Entry> path);
}
This problem is that I want to inject the persistence variable, but _internal requires the argument and _persistence is not ready yet.
2
Answers
Try with passing new instance in
_instance
. HereSpacesPersistenceImpl
is a class whichimplements
SpaceController
I simply grab a RiverPod provider, which gives me lazy initialization, discoverability as a singleton, and dependency injection via overrides for mocking during testing. Details at http://riverpod.dev/