Objective-C 无缝依赖注入框架
FlashCards+
Chegg – Textbooks, eTextbooks & Study Tools
您在使用 AppleGuice 而您的应用不在列表中吗? 给我留言。
AppleGuice 通过允许您轻松地将服务注入到任何类来帮助您编写干净、可重用和可测试的代码。其他依赖注入框架需要绑定、XML 编辑或使用特殊方法初始化您的类。使用 AppleGuice,您只需声明注入类型即可。作为额外收益,您仍然可以使用 `[[MyClass alloc] init]` 初始化类,这使得它与现有代码库的集成更加容易。
//AppDelegate.m
#import <AppleGuice/AppleGuice.h>
+(void) initialize {
[AppleGuice startService];
}
使用协议 AppleGuiceInjectable
标记您的可注入服务,这样 AppleGuice 就可以找到它。
@protocol MyServiceProtocol <AppleGuiceInjectable>
-(void) doStuff;
@end
@interface MyService : NSObject<MyServiceProtocol>
@end
@implementation MyService
...
@end
创建一个以 ioc 前缀(默认为 `_ioc_
`)为前缀的 ivar。在调用 init 方法时,AppleGuice 将自动注入适当的实现。
//MyClass.h
@interface MyClass : NSObject
@property (nonatomic, strong) id<MyServiceProtocol> ioc_myService;
@end
//MyClass.m
@implementation MyClass
//Now, you can use _ioc_myService anywhere. Even in the init function!
-(id) init {
self = [super init];
[self.ioc_myService doStuff];
return self;
}
@end
AppleGuice 无需手动绑定就初始化了 `_ioc_myService
`!
#import <AppleGuice/AppleGuice.h>
@implementation MyClassTests {
MyClass* classUnderTest;
}
-(void)setUp
{
[super setUp];
[AppleGuice startService];
[AppleGuice setInstanceCreationPolicy:AppleGuiceInstanceCreationPolicyCreateMocks];
classUnderTest = [[MyClass alloc] init];
}
-(void) test_foo_returnsValue {
//the injectable ivar is initialized with a mock. You can stub methods on it as you normally do with OCMock.
[[[classUnderTest.ioc_myService expect] andReturn:@"someString"] doStuff:OCMOCK_ANY];
[classUnderTest foo];
[classUnderTest.ioc_myService verify];
}
在测试时,AppleGuice 与 OCMock 搭配最为出色。
通过在类中声明一个ivar来实现服务注入。您可以在接口、实现中添加它,作为一个属性,甚至在其私有类中。AppleGuice会找到它。注入有三种口味
@interface MyClass () {
MyService* _ioc_MyService; //will create an instance of MyService.
id<MyServiceProtocol> _ioc_MyService //will create an instance of the first class conforming to MyServiceProtocol.
NSArray* _ioc_MyProtocol //will return an array containing instances of all classes conforming to MyProtocol
}
不需要在代码中弄乱共享实例声明或宏,只需将AppleGuiceSingleton
添加到实现协议列表中,AppleGuice将始终返回同一个实例。
@protocol MyServiceProtocol <AppleGuiceInjectable, AppleGuiceSingleton>
@end
只要相关类符合AppleGuiceSingleton
,AppleGuice就能处理注入类之间的循环依赖。
您可以将AppleGuice配置为注入代理对象而不是实际的服务。一旦需要服务(调用服务中的某个方法),代理将被替换为真实对象。
//add in your AppDelegate
[AppleGuice setInstanceCreationPolicy:AppleGuiceInstanceCreationPolicyLazyLoad];
查看快速的安装指南。
文档可以在这里找到。