We are using the package get_it:^7.1.3 for dependency injection. I want to register some classes with the same abstract class (like they were interfaces) and get them like:
List<AbstractLass> allClassesWhichImplementAbstractClass=di.sl.get<AbstractLass>();
Therefore I'd like to register it the following way:
sl.registerLazySingleton<AbstractLass>(() =>
AbstractLassImpl1());
sl.registerLazySingleton<AbstractLass>(() =>
AbstractLassImpl2());
But as I do that, I'll get an exception :
ArgumentError (Invalid argument(s): Object/factory with type AbstractLass is already registered inside GetIt. )
There is another solution where I register just the implementation the following way:
sl.registerLazySingleton<AbstractLassImpl1>(() =>
AbstractLassImpl1());
sl.registerLazySingleton<AbstractLassImpl2>(() =>
AbstractLassImpl2());
which works but then I would not access both by using their abstract class (if that is possible)
Can someone help me?
You can do it by providing instanceName parameter like so:
sl.registerLazySingleton<AbstractClass>(() =>
AbstractClassImpl1(), instanceName: 'implementation1');
sl.registerLazySingleton<AbstractClass>(() =>
AbstractClassImpl2(), instanceName: 'implementation2');
And use it also with the same name included:
sl.get<AbstractClass>(instanceName: 'implementation1');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With