map<T> method

Injector map<T>(
  1. ObjectFactoryFn<T> factoryFn,
  2. {bool isSingleton = false,
  3. String? key,
  4. bool allowFutureReassignment = false}
)

Maps the given type to the given factory function. Optionally specify the type as a singleton and give it a named key.

T The type the factoryFn will return an instance of.

factoryFn is a simple function which takes in an Injector and returns an new instance of the type T. In this method you can use the injector to get other dependencies this instance depends on (see examples below).

When isSingleton is true the first returned instances of the object is stored and subsequently return in future calls.

When key is provided the object is keyed by type name and the given key.

When allowFutureReassignment is provided the object mapping can be reassigned.

Throws an InjectorException if the type and or key combination has already been mapped.

Returns the current injector instance.

final injector = Injector.getInstance();
injector.map(Logger, (injector) => AppLogger());
injector.map(DbLogger, (injector) => DbLogger(), isSingleton: true);
injector.map(AppLogger, (injector) => AppLogger(injector.get(Logger)), key: "AppLogger");
injector.map(String, (injector) => "https://api.com/", key: "ApiUrl");

You can also configure mapping in a fluent programming style:

Injector.getInstance().map(Logger, (injector) => AppLogger());
                      ..map(DbLogger, (injector) => DbLogger(), isSingleton: true);
                      ..map(AppLogger, (injector) => AppLogger(injector.get(Logger)), key: "AppLogger");
                      ..map(String, (injector) => "https://api.com/", key: "ApiUrl");

Implementation

Injector map<T>(
  ObjectFactoryFn<T> factoryFn, {
  bool isSingleton = false,
  String? key,
  bool allowFutureReassignment = false,
}) {
  final objectKey = _makeKey(T, key);
  if (_factories.containsKey(objectKey) &&
      !_factories[objectKey]!.canReassign()) {
    throw InjectorException("Mapping already present for type '$objectKey'");
  }

  _factories[objectKey] = TypeFactory<T>(
    (i, p) => factoryFn(i),
    isSingleton,
    allowFutureReassignment,
  );

  return this;
}