I have an app that has about 11 different Singleton instances used throughout the many app's methods and classes; it's getting out of hand, and I want to replace all of them with dependency injection, like Typhoon. However, I am unable to find any doc, sample or mention of how to replace the singletons with dependency injection, including Typhoon. For instance, do I use multiple instances of Typhoon, replacing each singleton with an instance of Typhoon?
Edit: Pilgrim is the official Swift successor to Typhoon!!
Typhoon creator here. Yes, one of the uses of dependency injection it to provide the benefits of singletons without the drawbacks. But you don't necessarily need a library to apply the dependency injection pattern and replace your singletons. In fact it helps to understand the pattern by looking at how to implement it without a framework first:
Hollywood Principle: Don't call us, we'll call you
High level classes, like view controllers defer to collaborators to do their work. As you've mentioned you have around 11 of these. Now there's two ways to couple your class to the collaborator:
Seek out (call) the collaborator:
initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle
{
self = [super initWithNibName:nibname bundle:bundle];
if (self) {
_serviceClient = [MyServiceClient sharedInstance];
}
}
And the above way works, but its not good because:
The alternative:
Simply pass the collaborator in, via an init method or a property.
initWitServiceClient:(id<ServiceClient>)serviceClient
{
self = [super initWithNibName:@"MyNib" bundle:[NSBundle mainBundle];
if (self) {
_serviceClient = serviceClient;
}
}
How is this different to just . . . passing arguments?
Instead of hard-wiring a collaborator you pass it in as an argument. But now the next class up is hard-wired! So you keep doing this until you have a top level assembly class, that knows how to build your view controller (and other classes) from the individual pieces. If you do this:
Now Using Typhoon:
You'll have one retained instance of Typhoon per normal app. It will hold your singletons.
If after studying the above material you have a more specific question we'd be very happy to help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With