honk-di is a Guice-like dependency injector for (Java|Coffee)Script.
honk-di is a Guice-like dependency
injector for (Java|Coffee)Script.
The injector creates classes and resolves their dependencies. Take the following.
: consolelog "hi, "injector =user1 = injectorgetInstanceUseruser2 = injectorgetInstanceUserassert user1 !== user2
But what if we want only one User? We scope it!
@scope: 'singleton': consolelog "hi, "injector =user1 = injectorgetInstanceUseruser2 = injectorgetInstanceUserassert user1 === user2
Making a single class isn't going to save you much. What you want is for it to resolve your dependencies.
inject = require 'honk-di'@scope: 'singleton': consolelog "hi, "sayer: injectSayer: @sayersaynameinjector =user = injectgetInstanceUsersayer = injectgetInstanceSayerusersay'Jimmy'> Hijimmyusersayer === sayer> True
Note how DI's managed the singleton scope of the sayer for us. If we pulled out
User from the injector, it would be a new instance with the same
A binder is analogous to a Guice Module. But, seeing how "module" means something in the ol' Node.js world, they're called binders here.
Sometimes your dependencies get more complicated. Like, you may have a
that's just an in-memory mock for your test, but uses Google Maps in the UI, and
you're working on porting them to Leaflet. You can control this kind of malarkey
with DI pretty well.
inject = require 'honk-di': ->@bindMapViewtoGoogleMapView@bindUserStoretoMemUserStoreinScope'singleton'@bindConstant'api.root'to'/api/v1'
Now, the injector may consult some number of
Binders before creating an
instance. Say we have a controller as follows:
@scope: 'singleton': consolelog "hi, "view: injectMapViewusers: injectUserStoreapiRoot: inject'api.root': ->$get"/users"then @usersresetuserdone @viewrenderusers
Providers, complex scopes. I'm sure plenty of other small weird things.
The best DI apps have one call to
injector.getInstance. Passing the injector
around or pulling many instances out of it is likely a bad sign. Try to express
hairy sections as classes that have some number of dependencies and let DI
figure it out for you.