lite_ref 0.1.0 lite_ref: ^0.1.0 copied to clipboard
A lightweight dependency injection package with support for overriding for testing.
Overview #
Lite Ref is a lightweight dependency injection library for Dart and Flutter.
Why Lite Ref? #
-
Fast: Lite Ref doesn't use hashmaps to store instances so it's faster than all other DI libraries.
-
Safe: Lite Ref uses top level variables so it's impossible to get a NOT_FOUND error.
-
Lightweight: Lite Ref has no dependencies.
-
Simple: Lite Ref is simple to use and has a small API surface:
-
Create a singleton:
final dbRef = LiteRef(create: () => Database()); assert(dbRef.instance == dbRef.instance);
-
Use it:
final db = dbRef.instance; // or dbRef()
-
Override it (for testing):
dbRef.overrideWith(() => MockDatabase());
-
Freeze it (disable overriding):
dbRef.freeze();
-
Create a transient instance (always return new instance):
final dbRef = LiteRef(create: () => Database(), cache: false); assert(dbRef.instance != dbRef.instance);
-
Create a singleton asynchronously:
final dbRef = LiteAsyncRef(create: () async => await Database.init());
-
Use it:
final db = await dbRef.instance;
-
Use it synchronously:
// only use this if you know the instance is already created final db = dbRef.assertInstance;
-
Installation #
dart pub add lite_ref
Usage #
LifeRefs are lazy. They are only instantiated when you call instance
or ()
.
import 'package:lite_ref/lite_ref.dart';
// create a singleton
final dbRef = LiteRef(create: () => Database('example-connection-string'));
// use it
// refs are also callable so you can replace dbRef.instance with dbRef()
final db = dbRef.instance;
// override for testing
dbRef.overrideWith(() => MockDatabase());
// create a transient (always new instance) by setting cache to false
final userServiceRef = LiteRef(
create: () => UserService(database: db),
cache: false,
);