Skip to content

DI - Exported singleton binds are not shared between modules #666

@tspoke

Description

@tspoke

Describe the bug

When I use exported bind in a module, if I import this module the instance is not shared BUT the instance is re-created by each module.

In the example below, the AuthService constructor is called 2 times instead of 1 and the instance is different.

Even if my app architecture may be discussed, I expect a singleton in a DI system to be a singleton not a factory.

To Reproduce

class AppModule extends Module {
  @override
  List<Module> get imports => [AuthModule()];  // <<--- I need to import it to use the exported AuthenticatedHttpClient

  @override
  List<Bind> get binds => [
    Bind.singleton<AppEndpoints>((i) => AppEndpoints(i<AuthenticatedHttpClient>().client), export: false),
  ];

  @override
  List<ModularRoute> get routes => [
    ModuleRoute(Routes.auth, module: AuthModule()),  // AuthModule expose Routes too..
  ];
}

class AuthModule extends Module {
  @override
  List<Bind> get binds => [
    Bind.singleton<AuthenticatedHttpClient>((i) => AuthenticatedHttpClient.build(i(), AuthInterceptor(i())), export: true),
    Bind.singleton<AuthService>((i) => AuthService(i(), i()), export: true),
    Bind.factory<AuthController>((i) => AuthController(i(), i())),
    Bind.factory<AuthScreen>((i) => AuthScreen()),
  ];

  @override
  List<ModularRoute> get routes => [ChildRoute("/", child: (context, args) => AuthScreen())];
}

Expected behavior
When exporting a singleton, I expect the instance to be shared between different modules even if I import it multiple times.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions