|
Rules
#Introduction to Smartypants rules IntroductionThe Smartypants IOC system uses injector rules when deciding how to fulfil a request. DetailsEach rule essentially matches a key to an instance (either an implementation, or a provider, or another rule). A key consists of a Class (or interface) and an optional name. An example would be (IUIComponent named "BlueButton"). Adding a new rule is easy: Class Binding//Get our injector
injector = SmartyPants.getOrCreateInjectorFor(this);
//Add some rules
injector.newRule().whenAskedFor(IUIComponent).named("BlueButton").useClass(Button);
injector.newRule().whenAskedFor(IUIComponent).useClass(Canvas);This example demonstrates simple class binding, with the following meanings:
Instance Binding (singletons)injector.newRule().whenAskedFor(String).named("wsdl").useInstance("http://www.server.com/soap/service.wsdl");
injector.newRule().whenAskedFor(IService).useSingletonOf(com.company.ServiceImpl);In this example, we're binding:
Lazy singletons (useSingletonOf) are not created until they're needed, whereas useInstance binds to an existing instance. Provider Bindinginjector.newRule().whenAskedFor(Button).useProvider(myProviderInstance); Binds to an instance of a class that implements to Provider interface. Rule Bindinginjector.newRule().whenAskedFor(IUIComponent).named("RedButton").useRuleFor(IUIComponent, "BlueButton");This code redirects all requests for (IUIComponent named "RedButton") to whatever is bound to (IUIComponent named "BlueButton") Live rulesLive rules in Smartypants are the IOC equivalent to the Flex SDK's data-binding functionality. For example: [Bindable]
public var companyList : ArrayCollection;
injector.newRule().whenAskedFor(ArrayCollection).named("allCompanies").useBindableProperty(this, "companyList");This, combined with live injection (see the request documentation) allows you to make use Flex databinding between model and view classes without any direct coupling between them. |
Nice. Why not remove newRule() and put whenAskedFor directly on the injector?
No real reason, although I intend to add newRuleSet() to support "groups" of rules akin to Guice Modules, so the injector can resolve inter-dependants (but probably not cyclic dependencies since we have no proxy support in AVM2)
nice, i was gonna use SwiftSuspenders? (i'm still deciding) but i like more this syntax, and it has more options. The main reason why i cant decide is because idk why the people at robotlegs says SwiftSuspenders? is faster? idk. It wold be nice to have an answer if you can or want.