Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get_It Flutter Multiple Abstract Class Registration

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?

like image 540
Daniel Klauser Avatar asked May 19 '26 17:05

Daniel Klauser


1 Answers

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');
like image 100
Despotovic Avatar answered May 21 '26 14:05

Despotovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!