Dart: How to implement dagger like dependecy injection @MapInto and @StrinKey with get_it

36 views Asked by At

I'm using the get_it package in Dart for dependency injection, and I'm looking for a way to implement similar functionality of Java Dagger annotations @StringKey @MapInto in dart to eliminate the manual injection of the Map<String,Command> commands parameter in the CommandRouter constructor and find a more efficient way to inject the commands parameter into the CommandRouter class without performing manual configuration.

Here is the classes hierarchy:

abstract class Command {
  String key();
  Result handleInput(List<String> input);
}


@named
@Injectable(as: Command)
class HelloWorldCommand implements Command {
}


@named
@Injectable(as: Command)
class LoginCommand implements SingleArgCommand {
}

//The CommandRouter class is responsible for routing commands based on input and depends on a map of commands.

@injectable
class CommandRouter {
  Map<String, Command> commands = {};

  CommandRouter(@factoryParam Map<String, Command> commands) {
    commands = command;
  }
  Result route(String input) {
    
  }
}

main function:

void main(List<String> args) {
  configureDependencies();

   //this is the manual configuration I want to eliminate
   final originalMap = <String, Command>{
      'hello': getIt.get<Command>(instanceName: 'HelloWorldCommand'),
       'login': getIt.get<Command>(instanceName: 'LoginCommand'),
    };

   getIt.get<CommandRouter>(param1: originalMap).route(line);
}

if there's a more efficient or cleaner way to achieve the desired functionality.

0

There are 0 answers