injectable icon indicating copy to clipboard operation
injectable copied to clipboard

How to use scopes and environment filters?

Open dustincatap opened this issue 2 years ago • 0 comments

I am trying to register my scope first before calling $register and passing my custom EnvironmentFilter. But my dependencies annotated with my custom Environment are not registered.

@InjectableInit(
  initializerName: r'$register',
  preferRelativeImports: false,
  asExtension: false,
)
abstract final class ServiceLocator {
  static final GetIt instance = GetIt.instance..allowReassignment = true;

  static Future<void> registerDependencies() async {
    // We need to register forground services first
    initForegroundServiceScope(instance);

    // We need to manually override the pre-registered `EnvironmentFilter` with our new filter
    final environments = await _getEnvironments();
    final environmentFilter = NoEnvOrContainsAny(environments);
    instance.registerSingleton<EnvironmentFilter>(environmentFilter, instanceName: kEnvironmentsFilterName);

    await $register(instance, environmentFilter: environmentFilter);
  }

  static Future<Set<String>> _getEnvironments() async {
    // return custom environments based on current config...
  }
}

Upon checking, it seems that when registering a scope first, it registers a EnvironmentFilter with a instanceName using kEnvironmentsFilterName from get_it_helper.dart. This overrides the custom EnvironmentFilter I used in my $register. As a workaround I re-register my custom EnvironmentFilter.

Is this the expected behavior?

dustincatap avatar Apr 01 '24 15:04 dustincatap