0
我有点困惑尝试利用异议的依赖注入,为协议属性实例注入具体类。对于学习的目的,我做一个简单的记录器注入举例如下:异议依赖注入框架 - 绑定类到协议
// 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
现在我想注入我记录到一个视图属性,所以我做了以下内容:
// 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;
.
.
.
最后我有应用模块设置:
@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;
}
结果
一切似乎运行得很好,只有我的记录器属性是零在我的测试视图中,当我点击我的测试按钮来调用记录器语句。我希望它能够填充具体类类型CococoaLumberJackLogger的对象。
关于我哪里出错的任何想法?任何帮助是极大的赞赏。谢谢!
嗯,是的,我使用的故事板,所以我认为这是问题。我认为这是沿着这些路线的东西,但不确定是否有办法设置它,以便当视图控制器从故事板实例化时,会有一种方法让它引发喷射器被调用。感谢您的反馈。我一般是C#(最近asp mvc),并且已经使用了ninject/structuremap用于DI,我试图应用相同的模式。我会再玩一下,再次感谢! – Sean 2012-07-20 11:33:42
如果您使用故事板,您可以做的最好的事情是让控制器直接使用默认的喷油器。例如,logger = [[JSObjection defaultInjector] getObject:[TestLogger class]]。 – justice 2012-07-20 13:40:13
为了跟进,我现在正在调用注入器getObject,在我注入存储库的控制器的viewDidLoad方法中指定了我的协议,它运行良好 - 很好,谢谢! – Sean 2012-07-30 22:40:30