buildLazyRegisterFun method

Code buildLazyRegisterFun(
  1. DependencyConfig dep
)

Implementation

Code buildLazyRegisterFun(DependencyConfig dep) {
  String? funcReferName;
  Map<String, Reference> factoryParams = {};
  final hasAsyncDep = dependencies.hasAsyncDependency(dep);
  final isOrHasAsyncDep = dep.isAsync || hasAsyncDep;

  if (dep.injectableType == InjectableType.factory) {
    final hasFactoryParams = dep.dependencies.any((d) => d.isFactoryParam);
    if (hasFactoryParams) {
      funcReferName = isOrHasAsyncDep ? 'factoryParamAsync' : 'factoryParam';
      factoryParams.addAll(_resolveFactoryParams(dep));
    } else {
      funcReferName = isOrHasAsyncDep ? 'factoryAsync' : 'factory';
    }
  } else if (dep.injectableType == InjectableType.lazySingleton) {
    funcReferName = isOrHasAsyncDep ? 'lazySingletonAsync' : 'lazySingleton';
  }
  throwIf(funcReferName == null, 'Injectable type is not supported');

  final instanceBuilder =
      dep.isFromModule ? _buildInstanceForModule(dep) : _buildInstance(dep);
  final instanceBuilderCode = _buildInstanceBuilderCode(instanceBuilder, dep);
  final registerExpression = _ghLocalRefer.property(funcReferName!).call([
    Method(
      (b) => b
        ..lambda = instanceBuilderCode is! Block
        ..modifier = hasAsyncDep ? MethodModifier.async : null
        ..requiredParameters.addAll(
          factoryParams.keys.map(
            (name) => Parameter((b) => b.name = name),
          ),
        )
        ..body = instanceBuilderCode,
    ).closure
  ], {
    if (dep.instanceName != null)
      'instanceName': literalString(dep.instanceName!),
    if (dep.environments.isNotEmpty == true)
      'registerFor': literalSet(
        dep.environments.map((e) => refer('_$e')),
      ),
    if (dep.preResolve == true) 'preResolve': literalBool(true),
    if (dep.disposeFunction != null)
      'dispose': _getDisposeFunctionAssignment(dep.disposeFunction!)
  }, [
    typeRefer(dep.type, targetFile),
    ...factoryParams.values.map((p) => p.type)
  ]);
  return dep.preResolve
      ? registerExpression.awaited.statement
      : registerExpression.statement;
}