What are dependency injection approaches for Core Data in Swift?

Dependency Injection (DI) allows for better management of Core Data in Swift applications. It promotes code modularity and testability by decoupling the data layer from the rest of the application. This article explores different DI approaches for Core Data in Swift, including initializer injection, property injection, and service locator.
Dependency Injection, Core Data, Swift, initializer injection, property injection, service locator, testability, modularity
// Example of Dependency Injection in Core Data using Initializer Injection class DataManager { let persistentContainer: NSPersistentContainer init(persistentContainer: NSPersistentContainer) { self.persistentContainer = persistentContainer } func fetchEntities(entityName: String) -> [T]? { let fetchRequest = NSFetchRequest(entityName: entityName) do { let results = try persistentContainer.viewContext.fetch(fetchRequest) return results } catch { print("Failed to fetch: \(error)") return nil } } } // Usage: let persistentContainer = NSPersistentContainer(name: "Model") persistentContainer.loadPersistentStores { (storeDescription, error) in if let error = error { fatalError("Unresolved error \(error)") } } let dataManager = DataManager(persistentContainer: persistentContainer) let entities = dataManager.fetchEntities(entityName: "EntityName")

Dependency Injection Core Data Swift initializer injection property injection service locator testability modularity