Skip to content

Lightweight dependency injection framework built on Xcode macros

License

Notifications You must be signed in to change notification settings

yurii-lysytsia/Injector

Repository files navigation

Swift Injector with Xcode Macros

This project provides a lightweight dependency injection framework for Swift iOS projects built on Xcode macros. It simplifies dependency management by enabling you to mark classes with injectable properties and configure the Injector to resolve them during object creation.

Installation (SPM)

.package(url: "https://github.com/yurii-lysytsia/Injector.git", .upToNextMajor(from: "2.0.0"))

Usage

  1. Mark a class with injectable properties using the @Injectable macro. This macro informs the Injector about classes that participate in dependency injection.
@Injectable
class SomeInjectableMember { ... }
  1. Mark properties within the class as injectable using the @Injected macro. The Injector will resolve dependencies and inject them during object creation.
@Injected var int: Int
@Injected(name: "stringValue") var string: String // User `name: String` to define custom parameter's name
@Injected var intClosure: () -> Int
@Injected(escaping: true) var stringClosure: StringClosure // Use `escaping: true` to add `@escaping` modifier to init's parameter. Usually used for `typealias` closures
  1. Example
import Injector

@Injectable
public class SomeInjectableMember {
    public typealias StringClosure = () -> String

    // MARK: Injected
    
    @Injected var int: Int
    // Autogenerated code by `@Injected`
    //
    // {
    //     get {
    //         dependencies.int
    //     }
    // }
    @Injected(name: "stringValue") var string: String
    // Autogenerated code by `@Injected`
    //
    // {
    //     get {
    //         dependencies.stringValue
    //     }
    // }
    @Injected var intClosure: () -> Int
    @Injected(escaping: true) var stringClosure: StringClosure

    // MARK: Init
    
    init(dependencies: Dependencies) {
        self.dependencies = dependencies
    }
    
    // Autogenerated code by `@Injecable` macro
    //
    // public struct Dependencies {
    //     public let int: Int
    //     public let stringValue: String
    //     public let intClosure: () -> Int
    //     public let stringClosure: StringClosure
    //
    //     public init(
    //         int: Int,
    //         stringValue: String,
    //         intClosure: @escaping () -> Int,
    //         stringClosure: @escaping StringClosure
    //     ) {
    //         self.int = int
    //         self.stringValue = stringValue
    //         self.intClosure = intClosure
    //         self.stringClosure = stringClosure
    //      }
    // }
    //
    // private let dependencies: Dependencies
}

License

This project is distributed under the MIT License (see LICENSE file).

About

Lightweight dependency injection framework built on Xcode macros

Resources

License

Stars

Watchers

Forks

Languages