Search code examples
riverpodriverpod-generator

Dependency injection in a Riverpod AsyncNotifierProvider


I learn using Riverpod by following tips that I find online. Several sources spoke about dependency injection. This is an example of my implementation at the repository level:

@riverpod
UserRepository userRepository(UserRepositoryRef ref) {
  final Database db = ref.watch(databaseProvider);

  return UserRepository(
    db: db,
  );
}

class UserRepository {
  UserRepository({
    required Database db,
  }) : _db = db;

  final Database _db_;

  // ...
}

But now I try to inject this repository into my controller, which is an AsyncNotifierProvider. This is what it looks like so far:

@riverpod
class UserController extends _$UserController {
  final UserRepository _userRepository = UserRepository(db: Database());

  @override
  FutureOr<void> build() {}

  // ...
}

The first problem is that I'm not calling the repository via the userRepositoryProvider. I can't use ref when defining a field the way I do. The second problem is that I have no dependency injection.

I try adding a constructor with a parameter, but it generates an error so I guess that's not the right way to do.

So how should I do dependency injection in NotifierProvider and AsyncNotifierProvider ?


Solution

  • Whenever you want to access UserRepository in UserController, you access it using the Ref object. Ref is a property of AsyncNotifier.

    // inside build
    ref.watch(userRepositoryProvider)
    
    // other methods
    ref.read(userRepositoryProvider)