I have writted a factory pattern (which looks like dependency injection), which works perfectly:
protocol Dependency {
func resolveExtractIcon() -> ExtractIconService
}
class DependencyFactory: Dependency, HasDependencies {
func resolveExtractIcon() -> ExtractIconService {
return ExtractIcon()
}
}
// ---
struct DependencyInjector {
static var dependencies: Dependency = DependencyFactory()
private init() {}
}
protocol HasDependencies {
var dependencies: Dependency { get }
}
extension HasDependencies {
var dependencies: Dependency {
return DependencyInjector.dependencies
}
}
In my View controller i can call it like this:
class IOSAssetsViewController: NSViewController, HasDependencies {
private lazy var assetsViewModel: AssetsViewModelService = dependencies.resolveExtractIcon()
}
Now I would like to add in this design pattern a possibility to create an object once and each and inject it into the view controller that I want.
For example I have a viewModel associated with three view controllers in my project, I want that when I modify the viewModel in a ViewController while they are modified everywhere because they use the same instance, even if the ViewController does not exist as soon as it is created it will use the injected viewModel with the modifications made by the other view controllers.
I tried a lot of possibilities and I managed to make sure that only the view controllers create at the same time they access to the same instance, but the controllers that did not exist yet, of which it was to create then it accessed a new object and not the object changed by the view controller:
class DependencyFactory: Dependency, HasDependencies {
// Below it has allowed me to create a single instance accessible only to the view controller create at the same time
let resoledAssetsViewModel: AssetsViewModelService = AssetsViewModel(extractIconManager: ExtractIcon())
func resolveExtractIcon() -> ExtractIconService {
return ExtractIcon()
}
}
How can I make this design pattern to create a single instance for the viewmModel injected into the viewController?
As if I create viewModel in the appdelegate, and all my controllers call via AppDelegate and modify it. But I do not want to do it via the App delegate it's not beautiful, and not good practice. I want to do what I want by following my factory pattern
Thank you for your help :)
Aucun commentaire:
Enregistrer un commentaire