I'm trying to come up with a scalable solution for factory registration in Dart/Flutter using injectable (or any other DI library).
Currently, I explicitly create a factory class (BarFactory) for each type (Bar), and call their create method (in Foo.doSomething) to create the instance (Bar):
import 'package:injectable/injectable.dart';
@singleton
class Foo {
final BarFactory _barFactory;
Foo(this._barFactory);
void doSomething() {
var bar = _barFactory.create();
bar.blah();
}
}
@injectable
class BarFactory {
Bar create() => const Bar();
}
@injectable
class Bar {
const Bar();
void blah() {
/* ... */
}
}
The above dicatates writing a BarFactory for each Bar type. I can of course call getIt.registerFactory(() => Bar()) explicitly, but that's not much different from the above.
I tried to create a generic factory like this:
@injectable
class Factory<T> {
final T Function() create;
const Factory(this.create);
}
but that results in this error:
[SEVERE] injectable_generator:injectable_builder on lib/temp.dart:
Can not resolve function type
Try using an alias e.g typedef MyFunction = T Function();
which doesn't even make sense as T is a type parameter...
Any ideas on how to achieve this? I'm open to using a different DI library if it helps.