Aspyct.org

APServiceBox update: self-injection

| Comments

Small update to APServiceBox, adding the NSObject+APServiceBox category and the defaultBox method. These two allow you to make objects that will themselves ask for dependencies. This contributes to reduce the amount of code, and in some cases facilitates some difficult situations.

Read more about APServiceBox on its dedicated page.

The first thing you should do is register your services and other dependencies into the default service box.

1
2
3
4
5
AnalyticsManager *analyticsManager = [[AnalyticsManager alloc] init];
[[APServiceBox defaultBox] registerDependency:analyticsManager as:@"analyticsManager"];

// Or you can create your own box
APServiceBox *myBox = [[APServiceBox alloc] init];

Then 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
@interface MyViewController
@property (strong, nonatomic) AnalyticsService *analyticsService;
@end


#import "NSObject+APServiceBox.h"
@implementation MyViewController

- (id)init {
    self = [super init];

    if (self) {
        // This will ask the [APServiceBox defaultBox] to provide available dependencies
        [self fillWithDependencies];
    }

    return self;
}

@end

Comments