Swinject 返回 nil,因为对象注册错误

Posted

技术标签:

【中文标题】Swinject 返回 nil,因为对象注册错误【英文标题】:Swinject returns nil because object is wrong registered 【发布时间】:2020-12-28 11:09:26 【问题描述】:

这就是我为FirebaseMessaging注册对象的方式:

    container.register(Messaging.self)  _ in
        return Messaging.messaging()
    

然后我需要使用它:

    container.register(NotificationSchedulerable.self)  resolver in
        let userNotificationCenter = resolver.resolve(UNUserNotificationCenter.self)!
        let messaging = resolver.resolve(Messaging.self)! //unexpectadly found nil
        return NotificationScheduler(userNotificationCenter: userNotificationCenter, messaging: messaging)
    

但我收到一个错误:

Swinject:解析失败。预计注册: 服务:FIRMessaging,工厂:解析器 -> FIRMessaging 可用注册: 服务:FIRMessaging,工厂:解析器 -> FIRMessaging,ObjectScope:图 致命错误:在展开可选值时意外发现 nil:文件 ToolsAssembly.swift,第 72 行

为什么会这样?

【问题讨论】:

【参考方案1】:

也许问题是你必须注册一个 FIRMessaging 而不是 Messaging

https://firebase.google.com/docs/cloud-messaging/ios/client?hl=es

像这样:

    container.register(FIRMessaging.self)  _ in
        return Messaging.messaging()
    

然后:

container.register(NotificationSchedulerable.self)  resolver in
        let userNotificationCenter = resolver.resolve(UNUserNotificationCenter.self)!
        let messaging = resolver.resolve(FIRMessaging.self)! //unexpectadly found nil
        return NotificationScheduler(userNotificationCenter: userNotificationCenter, messaging: messaging)
    

【讨论】:

【参考方案2】:

我可以邀请您查看 Swift 的新 DIContainer 吗?

在这个库中,您可以使用属性包装器访问您的依赖项。

@Injected(.githubService)
var githubService: FetchService

@Injected(.by(type: FetchService.self, withKey: "gitlab"))
var gitlabService: FetchService

@InjectedSafe
var externalService: ExternalSingletonService?

我希望它很适合你的需要。

【讨论】:

【参考方案3】:

您应该在解决依赖关系之前调用FirebaseApp.configure()

【讨论】:

以上是关于Swinject 返回 nil,因为对象注册错误的主要内容,如果未能解决你的问题,请参考以下文章

Swinject:生成任何对象的实例(对于未注册的对象、ViewModel 等...)

当对象范围为容器时,多次调用 Swinject 工厂关闭

Swinject:使用弱范围会泄漏对象

每次使用 Swinject 解析对象时如何返回相同的实例?

Swinject注册UIViewController最佳实践

使用 swinject 注册具有关联类型的协议时出现问题