mapWithParams<T> method

Injector mapWithParams<T>(
  1. ObjectFactoryWithParamsFn<T> factoryFn, {
  2. String? key,
  3. bool allowFutureReassignment = false,
})

Maps the given type to the given factory function. Optionally 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, params) => AppLogger(params["logKey"]));
injector.map(AppLogger, (injector, params) => AppLogger(injector.get(Logger, params["apiUrl"])), key: "AppLogger");

Implementation

Injector mapWithParams<T>(
  ObjectFactoryWithParamsFn<T> factoryFn, {
  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>(
    factoryFn,
    false,
    allowFutureReassignment,
  );

  return this;
}