123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- import 'dart:async';
- import 'package:get_it/get_it.dart';
- import 'package:lszlgl/main.dart';
- /// 依赖注入管理
- ///
- /// ```
- /// 简单使用
- /// 添加注入:
- /// var user = Inject.put<UserBean>(UserBean(), dispose: (v) => v.dispose());
- /// 添加注入(懒加载):
- /// Inject.putLazy(UserBean(), dispose: (v) => v.dispose());
- ///
- /// 获取实例:
- /// var user = Inject.get<UserBean>();
- ///
- /// 移除注入:
- /// Inject.remove<UserBean>();
- /// ```
- class Inject {
- Inject._();
- /// 添加依赖注入
- /// 注入后得到实例化对象, 也可以通过[get]方法得到对象.
- /// * [instance] 实例化对象
- /// * [name] 注入多个同类型对象时,可以使用name来区分
- /// * [dispose] 移除时回调方法
- /// * [allowReassignment] 是否可以重复注册, 默认不可重复注册, 返回之前已有实例
- ///
- static T put<T extends Object>(
- T instance, {
- String? name,
- FutureOr Function(T)? dispose,
- bool allowReassignment = false,
- }) {
- GetIt.I.allowReassignment = true;
- // 不可重复注册, 已注册,则返回之前实例
- if (!allowReassignment && GetIt.I.isRegistered<T>(instanceName: name)) {
- logger.d('Inject put:$T 已被注册');
- return get<T>()!;
- }
- logger.d('Inject put:$T');
- GetIt.I.registerSingleton<T>(
- instance,
- instanceName: name,
- dispose: dispose,
- );
- return instance;
- }
- /// 添加依赖注入 懒加载
- /// 注入后不会立即实例化对象, 当调用[get]时才会实例化.
- /// * [factoryFunc] 实例化对象回调方法
- /// * [name] 注入多个同类型对象时,可以使用name来区分
- /// * [dispose] 移除时回调方法
- static void putLazy<T extends Object>(
- T Function() factoryFunc, {
- String? name,
- FutureOr Function(T)? dispose,
- bool allowReassignment = false,
- }) {
- GetIt.I.allowReassignment = true;
- if (!allowReassignment && GetIt.I.isRegistered<T>(instanceName: name)) {
- logger.d('Inject putLazy:$T 已被注册');
- return;
- }
- logger.d('Inject putLazy:$T');
- GetIt.I.registerLazySingleton<T>(
- factoryFunc,
- instanceName: name,
- dispose: dispose,
- );
- }
- /// 移除依赖注入
- /// * [instance] 通过实例移除
- /// * [name] 通过名称移除
- /// * [dispose] 移除时回调方法
- static FutureOr remove<T extends Object>({
- Object? instance,
- String? name,
- FutureOr Function(T)? dispose,
- }) {
- logger.d('Inject remove:$T');
- return GetIt.I.unregister(
- instance: instance,
- instanceName: name,
- disposingFunction: dispose,
- );
- }
- /// 获取唯一实例
- /// Model model = GdInject.get<Model>();
- static T? get<T extends Object>({String? name}) {
- logger.d('Inject get:$T');
- return GetIt.I.get<T>(instanceName: name);
- }
- /// 获取唯一实例,如果未注入依赖,将自动注入依赖
- static T getAndPut<T extends Object>(
- T instance, {
- String? name,
- FutureOr Function(T)? dispose,
- }) {
- // 已注册
- if (GetIt.I.isRegistered<T>(instanceName: name)) {
- return get<T>(name: name)!;
- }
- return put<T>(instance, name: name, dispose: dispose);
- }
- }
|