What is it ?
APServiceBox is a dependency injection container that can be used in your iOS or other Objective-C projects. It can be compared in some way to containers such as Spring, but a much more simple one.
Use this box when you have services or objects that must be available throughout the application. For example, if all your *ViewControllers need to report analytics, or depend on a single data source.
APServiceBox is open-source (MIT licensed) and therefore free to use.
How to use
Grab the whole thing from its github repository or download the zipball, and drop the classes into your project.
The first thing you should do is register your services and other dependencies into the default service box.
1 2 3 4 5
The easiest way to inject dependencies is to call the
fillWithDependencies method in the
init of an object. This will use the default service box to fill the current object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
There are two conditions for a dependency to be injected:
- the @property name corresponds to the name given when registering the service
- the @property type matches the registered service, that is (one of the following):
- service.class == @property.class
- [service isKindOfClass:@property.class]
- [service.class conformsToProtocol:@property.protocol]
Thus, the following two forms of properties are valid:
1 2 3 4 5
Inject from outside the class
1 2 3 4 5 6 7 8 9 10 11 12 13
Inject the box itself
If you need to inject the box itself into one of the objects (typically a UIViewController that will create other UIViewControllers), you can simply add a @property of type APServiceBox and named “serviceBox”.
When you call
fill: for the first time, APServiceBox will scan and fill each of the registered dependencies. This allows the following scenario:
1 2 3
1 2 3 4 5
1 2 3 4 5 6 7 8 9
If you need more insights on how this works, have a look at the test file: it’s short and clear! Or contact me ;)
You can either
- fork the repository, fix and make a pull request (don’t forget the unit tests)
- create a new ticket in the issue tracker
- send me a mail to firstname.lastname@example.org
- contact me via twitter: @aspyct
Feel free to use this for commercial works, and I’d be glad to hear from you, or why not see my name in a “thanks” section :)
This code is available under the MIT license.
Hope you like this little utility. Have fun!