For those of you that are familiar with the how and why of dependency injection (DI), we’ve created a DI framework for Objective-C called Objection. Those familiar with Google’s Guice will feel right at home with Objection.
We have long wanted DI for Objective-C.
Objection was our answer.
Why use this dependency injection stuff?
DI separates the components of the application in a clean way. It builds and composes the objects of the application. This separation makes code more test friendly. Mock objects can easily be injected into tests to keep the unit tests focused on what needs to be tested.
What does it look like?
Basic Usage
A class can be registered with objection using the macros objection_register
or objection_register_singleton
. The objection_requires
macro can be used to declare what dependencies objection should provide to all instances it creates of that class. objection_requires
can be used safely with inheritance.
Fetching Objects from Objection
An object can be fetched from objection by creating an injector and then asking for an instance of a particular class. An injector manages its own object context, which means that a singleton is per injector and not necessarily a true singleton.
A global injector can be registered with Objection which can be used throughout your application or library.
Can it be suitable for creation of UIViewController?
It is not currently suitable for instantiating view controllers. Objection does not take constructor hints (ie initWithStyle: with the proper style). There also frameworks that dictate the instantiation of controllers like three20 which would not go through objection to create the controller. Rendering Objection useless.
You can, however, ask for a controller’s dependencies directly from objection once it is instantiated.
E.g. self.model = [Objection getObject:[MyModel class]];
Good stuff! I was jus thinking about writing something like this myself. Thanks for saving me the work. You should do a follow-up post on unit testing with Objection.
Thanks Chris,
Yes we should probably expose a couple of the test helpers we use to ensure an object is properly registered with Objection. We currently have a couple of helpers that prove an object can be constructed and that it is setup with the correct dependencies. We’ll follow up with a blog post soon.
Let me know how you like Objection.