Skip to content

DIContainer is lightweight dependency injection container framework for Swift

License

Notifications You must be signed in to change notification settings

minsOne/DIContainer

Repository files navigation

Dependency Injection Container

English | 한국어

Overview

The Swift Dependency Injection Container is a lightweight and flexible library designed to facilitate dependency management in Swift applications. It provides a structured and type-safe approach to resolve dependencies throughout your codebase, promoting code reusability, testability, and maintainability.

Features

  • Type-safe dependency resolution.
  • Lazy instantiation of dependencies.
  • Property wrappers for convenient dependency injection.
  • Dynamic module registration and management.
  • Result builder syntax for declarative module registration.
  • Debug utilities for module and injection key scanning.

Requirements

  • Swift 5.9+

Installation

DIContainer is available Swift Package Manager.

Swift Package Manager

in Package.swift add the following:

dependencies: [
    .package(url: "https://github.com/minsOne/DIContainer.git", from: "1.0.0")
]

Usage

Basic Usage

First, register a key and module pair to a Container, where the module has concreate type. Key has protocol type, and concreate type is inheriting protocol type

Container {
    Module(AnimalKey.self) { Cat() }
}
.build()

Then get an instance from the container.

@Inject(AnimalKey.self)
var cat: Meow
cat.doSomething() // prints "Meow.."

Where definitions of the protocols and struct are

class AnimalKey: InjectionKey {
    var type: Meow?
}

protocol Meow {
    func doSomething()
}

struct Cat: Meow {
    func doSomething() {
        print("Meow..")
    }
}

Test

$ (cd MockData/Sources/MockData && for i in {1..20}; do cp MockClass.swift MockClass$i.swift; done)
$ swift test
$ swift test -Xswiftc -O

Contributing

Contributions to the Swift Dependency Injection Container are welcome. Here are ways you can contribute:

  • Reporting issues
  • Suggesting enhancements
  • Submitting pull requests with bug fixes or new features

Please ensure to follow the coding standards and write tests for new functionality.

License

This project is licensed under the MIT License.

Post

Credits

The DIContainer are inspired by: