【问题标题】:Flutter injectable - Inject one singleton for several interfacesFlutter injectable - 为多个接口注入一个单例
【发布时间】:2022-12-10 07:43:49
【问题描述】:

我正在尝试注册一个实现两个接口的类的单例。那可能吗?生成器指出,一个接口不是它自己的子类型。

abstract class IOne { ... }
abstract class ITwo { ... }

@module
abstract class RegisterMySingleton {
  @LazySingleton(as: IOne)
  IOne get one => getIt<MySingleton>();
  @LazySingleton(as: ITwo )
  ITwo get two => getIt<MySingleton>();
}

@lazySingleton
class MySingleton implements IOne, ITwo { ... }

flutter pub run build_runner build --delete-conflicting-outputs 的输出

[IOne] is not a subtype of [IOne]

【问题讨论】:

    标签: flutter code-injection injectable


    【解决方案1】:

    也许对你来说为时已晚@Matthias,但也许有人会觉得这有帮助。 我能够像这样解决上面的问题(即使它在架构上有争议):

    @module
    abstract class AppModule {
      @preResolve
      Future<Repository> get repository => RepositoryImpl.init();
    
      @injectable
      MyServiceImpl get myService(Repository repository) => MyServiceImpl(repository);
    
      @injectable 
      One get one(MyServiceImpl myService) => myService;
    
      @injectable 
      Two get two(MyServiceImpl myService) => myService;
      
      @injectable 
      Three get three(MyServiceImpl myService) => myService;
    }
    

    PS:为了清楚起见,单例模式是一种将类的实例化限制为一个对象的设计模式。 DI 不保证系统中只有一个实例。 “DI 系统”中通常只有一个实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 2018-10-03
      • 2017-01-20
      • 1970-01-01
      • 2011-10-20
      相关资源
      最近更新 更多