Skip to content

Repository files navigation

InjectPropertyWrapper

Provides a generic Swift @Inject property wrapper that can be used to inject objects / services from a dependency injection framework of your choice.

Basic Usage

First, you need to implement the Resolver protocol for the Dependency Injection (DI) framework you are using.

For example, when using Swinject:

extensionContainer:InjectPropertyWrapper.Resolver{}

In case of Swinject the Container class already contains a method with the same signature (resolve<T>(_ type: T, name: String?)) as the InjectPropertyWrapper Resolver protocol requires.

Then you need to set the global resolver (for example in your app delegate):

letcontainer=Container()InjectSettings.resolver = container

Register some objects in the container:

container.register(APIClient.self){ _ inAPIClient()}
container.register(MovieRepository.self){ _ inIMDBMovieRepository()}
container.register(MovieRepository.self, name:"netherlands"){ _ inIMDBMovieRepository("nl")}

Now you can use the @Inject property wrapper to inject objects/services in your own classes:

classIMDBMovieRepository:MovieRepository{@InjectprivatevarapiClient:APIClient...func fetchTop10(completionHandler:@escaping(movies:[Movie])->Void){...}}classMovieViewModel:BindableObject{publicvardidChange=PassthroughSubject<Void,Never>()publicprivate(set)vartop10:[Movie]?{
didSet {
didChange.send()}}@InjectprivatevarmovieRepository:MovieRepositoryfunc load(){
movieRepository.fetchTop10(){[weak self] movies inself?.top10 = movies
}}}

It is also possible to inject different objects of the same type using the name parameter:

classMovieViewModel:BindableObject{...@InjectprivatevarglobalMovieRepository:MovieRepository@Inject(name:"netherlands")privatevarnlMovieRepository:MovieRepository...}

Normally if the property wrapper is unable to resolve a dependency it will raise a non-recoverable fatal error. If for some reason you expect an object sometimes to be unavailable in your container, you can mark the property as optional:

classMovieViewModel:BindableObject{...@Inject(name:"germany")privatevardeMovieRepository:MovieRepository?...}

Testing

To run the tests for this package make sure the ENABLE_TESTS environment variable is set to 1 or true. For example when using the command line:

ENABLE_TESTS=1 swift test

This allows the package to only load certain dependencies when testing.

License

This project is licensed under the terms of the MIT license. See the LICENSE file.

About

Swift @Inject Property Wrapper

Resources

Stars

47 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages