69 lines
2.2 KiB
Dart
69 lines
2.2 KiB
Dart
library;
|
|
|
|
import 'package:fluttery/logger/logger.dart';
|
|
import 'package:fluttery/preferences/preferences.dart';
|
|
import 'package:fluttery/src/logger/logger_impl.dart';
|
|
import 'package:fluttery/src/preferences/preferences_impl.dart';
|
|
import 'package:kiwi/kiwi.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
/// A class to manage services.
|
|
class App {
|
|
static final _AppService _appService = _AppService();
|
|
|
|
/// Registers a service with a factory function to instantiate the implementation.
|
|
///
|
|
/// This ensures that the implementation is created when the service is requested.
|
|
///
|
|
/// `implFactory` - A factory method to create the service implementation.
|
|
static void registerService<T extends Service>(T Function() implFactory) {
|
|
_appService.registerSingleton<T>(implFactory);
|
|
}
|
|
|
|
/// Retrieves the registered service.
|
|
///
|
|
/// Returns an instance of the registered service.
|
|
static T service<T extends Service>() {
|
|
return _appService.resolve<T>();
|
|
}
|
|
|
|
/// Registers the default services required by the application.
|
|
static void registerDefaultServices() {
|
|
registerService<Logger>(() => LoggerImpl());
|
|
|
|
SharedPreferences.getInstance().then((instance) {
|
|
registerService<Preferences>(() => PreferencesImpl(instance: instance));
|
|
});
|
|
}
|
|
}
|
|
|
|
/// Abstract class to represent a service.
|
|
abstract class Service {}
|
|
|
|
/// Internal class to manage the registration and resolution of services.
|
|
class _AppService {
|
|
static _AppService? _singleton;
|
|
|
|
static final KiwiContainer _kiwi = KiwiContainer();
|
|
|
|
/// Factory constructor to ensure singleton instance of _AppService.
|
|
factory _AppService() => _singleton ??= _AppService._();
|
|
|
|
/// Private constructor.
|
|
_AppService._();
|
|
|
|
/// Registers a singleton service with a factory function to create the instance.
|
|
///
|
|
/// `serviceFactory` - A factory method to create the service implementation.
|
|
void registerSingleton<T extends Service>(T Function() serviceFactory) {
|
|
_kiwi.registerFactory<T>((c) => serviceFactory());
|
|
}
|
|
|
|
/// Resolves and retrieves the registered service.
|
|
///
|
|
/// Returns an instance of the registered service.
|
|
T resolve<T extends Service>() {
|
|
return _kiwi.resolve<T>();
|
|
}
|
|
}
|