Reputation: 346
I'm a bit confused trying utilize Objection for dependency injection, to inject a concrete class for a protocol property instance. For learning purposes I was making a simple logger injection example as follows:
// Protocol definition
@protocol TestLogger<NSObject>
-(void)trace: (NSString*) message, ...;
-(void)info: (NSString*) message,...;
-(void)warn: (NSString*) message,...;
-(void)error: (NSString*) message, ...;
@end
// Concrete class definition following my protocol - note it doesn't actually use
// CocoaLumberjack yet, I just had an NSLog statement for testing purposes
@interface CocoaLumberjackLogger : NSObject<TestLogger>
@end
// Implementation section for lumberjack logger
@implementation CocoaLumberjackLogger
-(void)trace: (NSString*) message, ...
{
va_list args;
va_start(args, message);
[self writeMessage:@"Trace" message:message];
va_end(args);
}
//(note: other implementations omitted here, but are in my code)
.
.
.
@end
Now I want to inject my logger into a view as a property so I do the following:
// My test view controller interface section
@interface TestViewController : UIViewController
- (IBAction)testIt:(id)sender;
@property id<TestLogger> logger;
@end
// Implementation section
@implementation TestViewController
objection_register(TestViewController)
objection_requires(@"logger")
@synthesize logger;
.
.
.
Lastly I have the application module setup:
@interface ApplicationModule : JSObjectionModule {
}
@end
@implementation ApplicationModule
- (void)configure {
[self bindClass:[CocoaLumberjackLogger class] toProtocol:@protocol(TestLogger)];
}
@end
@implementation TestAppDelegate
@synthesize window = _window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions
{
JSObjectionModule *module = [[ApplicationModule alloc] init];
JSObjectionInjector *injector = [JSObjection createInjector:module];
[JSObjection setDefaultInjector:injector];
return YES;
}
The outcome
Everything seems to run perfectly fine, only my logger property is nil in my test view when I click my test button to call a logger statement. I was hoping it would have been filled out with an object of concrete class type CococoaLumberJackLogger.
Any ideas as to where I went wrong? Any help is greatly appreciated. Thanks!
Upvotes: 0
Views: 1385
Reputation: 400
Sean,
What is responsible for initializing the TestViewController? The TestViewController's initialization must be delegated to the injector.
For example, if a NIB is responsible for instantiating it then the logger would be nil because the NIB has no understanding of TestViewController's dependencies.
Upvotes: 2