[英]SwiftUI Dependency injection with environment object
I'm trying to create som kind of solution for injecting dependencies to SwiftUI view models and I have no idea whether I'm on to something or if I need to take this back to the drawing table.我正在尝试创建某种解决方案,用于将依赖项注入 SwiftUI 视图模型,但我不知道我是否正在做某事,或者是否需要将其带回绘图表。
struct MyAppName: App {
private static var serviceToInject = ServiceToInject()
@StateObject var viewModel1 = ViewModel1(service: serviceToInject)
@StateObject var viewModel2 = ViewModel2(service: serviceToInject)
var body: some Scene {
WindowGroup {
if authenticationViewModel.isLoggedIn {
HomeView()
.environmentObject(viewModel1)
.environmentObject(viewModel2)
} else {
LoginView()
.environmentObject(viewModel2)
}
}
}
Is this a possible to solution?这是一个可能的解决方案吗? I'm concerned about the use of static on the service.
我担心在服务上使用 static。 Is this maybee a better way to do it:
这也许是一种更好的方法:
struct MyAppName: App {
@StateObject var viewModel1 = ViewModel1(service: ServiceToInject())
@StateObject var viewModel2 = ViewModel2(service: ServiceToInject())
var body: some Scene {
WindowGroup {
if authenticationViewModel.isLoggedIn {
HomeView()
.environmentObject(viewModel1)
.environmentObject(viewModel2)
} else {
LoginView()
.environmentObject(viewModel2)
}
}
}
If I understand right, you want to inject an object to multiple instances.如果我理解正确,您想将 object 注入多个实例。 You can make the ServiceToInject object an @EnvironmentObject, this way you can send it to multiple other classes: https://www.hackingwithswift.com/quick-start/swiftui/what-is-the-environmentobject-property-wrapper
您可以将 ServiceToInject object 设为 @EnvironmentObject,这样您就可以将其发送到多个其他类: https://www.hackingwithswift.com/quick-start/swiftui/what-is-the-environmentobject-property-wrapper
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.