Dependency Injection
This package provides a simple and easy-to-use Dependency Injection (DI) solution for Swift projects. It is inspired by JSR-330 and uses a property wrapper named @Inject to inject dependencies into properties of classes, structs, and protocols.
Features
- Support for both
prototypeandsingletonscopes Initialisableprotocol for classes with aninitmethodInjectableprotocol for objects that conform toInitialisableWeakObjectWrapperclass for wrapping reference types as weak referencesInjectstruct for property wrapper, allowing for the injection of dependencies into propertiesContextclass for managing the registration and resolution of dependenciesAssemblyBuilderclass for creating and configuring anAssemblyof dependencies
Usage
-
Import the
DependencyInjectionmodule in your project. -
Use the
@Injectproperty wrapper on properties in your classes, structs, and protocols.
class MyClass {
@Inject var dependency: MyDependency
}
- Use the
AssemblyBuilderto register your dependencies and configure the scope.
let assembly = AssemblyBuilder.instance
.add(factory: { MyDependency() }, bindingName: "MyDependency", scope: .singleton)
.build()
- Use the
Contextclass to register the assembly and resolve the dependencies (in AppDelegate for example)
Context.instance.register(assembly)
Compatibility
This library requires Swift 5.3 or later.
Installation
You can install DependencyInjection using the Swift Package Manager by adding it as a dependency in your Package.swift file or adding it to your Xcode project.
Contributing
I welcome contributions and suggestions for improvements to this library. If you find a bug or want to propose a new feature, please open an issue or submit a pull request.
Authors
- Denis Murphy
License
This code is licensed under the MIT License.