tschneidereit / SwiftSuspenders

NOTE: Find the offical repo at http://github.com/robotlegs/swiftsuspenders
https://github.com/robotlegs/swiftsuspenders
MIT License
280 stars 89 forks source link

Implement factory injection #21

Closed tschneidereit closed 12 years ago

tschneidereit commented 14 years ago

Instead of letting SwiftSuspenders directly handle the creation of injected values, it might sometimes be useful to delegate that to a factory. sammyt's Dawn framework supports factory injections, which looks like a perfect match for this functionality.

Syntax proposal:

Injector#mapFactoryClass(whenAskedFor : Class, useFactoryClass : Class, named : String = '');

and

Injector#mapFactory(whenAskedFor : Class, useFactoryInstance : Object, named : String = '');

The second option will enabled configuring a specific instance of the factory. It might be more useful to use child injectors for configuring the factory itself.

texastoland commented 14 years ago

Should the first snippet read Injector#mapFactoryClass()? What is a factory? Did you like his Provider annotation? That could negate any inter-library interface dependency.

tschneidereit commented 14 years ago

Yes, that's what I meant, thanks. I've corrected the text.

I like the [Provider] annotation indeed: Much better than to prescribe an interface for the factory. Also, it enables multiple factory methods in one class, each annoted with [Provider] and selected by its return type.

I haven't found any standard annotations, but will look some more. If Guice or Spring support something similar, it might be worthwhile to use they annoation syntax.

texastoland commented 14 years ago

I hadn't considered multiple Providers brilliant!

tschneidereit commented 12 years ago

Instead of explicitly supporting factory mappings, Swiftsuspenders 2 will have a generic way of mapping to custom providers that only need to implement the method apply(targetClass:Class, usingInjector:Injector):Object. To make it easier to use the custom provider, Swiftsuspenders 2 comes bundled with a FactoryProvider that takes a Class implementing DependencyProvider as a ctor argument and construct an instance of that class for each application, enabling easy implementation of DepencyProviders with their own dependencies.