我一直在学习有关依赖注入(inject)的知识,现在我已经在dart中实现了一个示例。但是我遇到了与get_it包有关的问题。这是代码:
'MessageService.dart'

abstract class MessageService {
  void sendMessage(String msg, String rec);
}

class EmailServiceImpl implements MessageService {
  @override
  void sendMessage(String message, String receiver) {
    //logic to send email
    print("Email sent to $receiver with message $message.");
  }
}

class SMSServiceImpl implements MessageService {
  @override
  void sendMessage(String message, String receiver) {
    //logic to send SMS
    print("SMS sent to $receiver with message $message.");
  }
}

'injection_container.dart'
import 'package:get_it/get_it.dart';

import 'MessageService.dart';
import 'main.dart';

final getIt = GetIt.instance;

void init() async {
  getIt.registerFactory<Client>(() => Client());
  getIt.registerFactory<MyApplication>(() => MyApplication(EmailServiceImpl()));
  getIt.registerFactory<MessageService>(() => EmailServiceImpl());
  getIt.registerFactory<MessageService>(() => SMSServiceImpl());
}
'main.dart'
import 'MessageService.dart';
import 'injection_container.dart' as di;

void main() {
  di.init();
  di.getIt<Client>().send();
}

class MyApplication {
  MessageService _service;

  MyApplication(this._service);

  void processMessages(String msg, String rec) {
    //do some msg validation, manipulation logic etc
    this._service.sendMessage(msg, rec);
  }
}

class Client {
  void send() {
    MyApplication app = di.getIt<MyApplication>();
    app.processMessages("Hi Bill", "[email protected]");
  }
}
但是,在injection_container.dart中同时注册EmailServiceImpl和SMSServiceImpl时,出现以下错误:未处理的异常:无效的参数:MessageService类型的对象/工厂已在GetIt中注册。
如果我注释掉SMSServiceImpl注册,它可以正常工作。有人可以说出什么问题吗?
如果有人可以查看我的依赖注入(inject)示例,这将很有帮助。这是呈现依赖注入(inject)的正确方法吗?

最佳答案

getIt.registerFactory<MessageService>(() => EmailServiceImpl()); getIt.registerFactory<MessageService>(() => SMSServiceImpl());GetIt仅允许(默认情况下)一个类型的实例。
因此,您的代码正在尝试注册相同类型的两个实例(MessageService)。
从GetIt文档

因此,当您调用GetIt.I.get()时,它将不会知道它是EmailServiceImpl还是SMSServiceImpl
试试这个getIt.registerFactory<EmailServiceImpl>(() => EmailServiceImpl()); getIt.registerFactory<SMSServiceImpl>(() => SMSServiceImpl());您还可以允许重新声明,以便您的代码按原样工作。GetIt.I.allowReassignment = true

关于flutter - 依赖注入(inject)问题并在Flutter中获得,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/64523760/

10-11 21:44