Working example
ciscoheat edited this page Oct 18, 2010
·
5 revisions
Here's a functional example that you can paste into a Main.hx for trying out unject:
Main.hx
package ;
import unject.StandardKernel;
import unject.UnjectModule;
import haxe.rtti.Infos;
class Main
{
public static function main()
{
var kernel = new StandardKernel([new TestModule()]);
var samurai = kernel.get(Samurai);
var katana = kernel.get(Katana);
trace(samurai.attack("the evildoers"));
trace("The katana has sharpness " + katana.sharpness);
}
}
class TestModule extends UnjectModule
{
public override function load()
{
bind(Katana).toSelf().withParameter("sharpness", 100);
bind(Samurai).toSelf();
bind(IWeapon).to(Sword);
}
}
class Katana implements Infos
{
public var sharpness : Int;
public function new(sharpness : Int)
{
this.sharpness = sharpness;
}
}
class Samurai implements Infos
{
var weapon : IWeapon;
public function new(weapon : IWeapon)
{
this.weapon = weapon;
}
public function attack(target : String)
{
return weapon.hit(target);
}
}
class Sword implements IWeapon, implements Infos
{
public function new();
public function hit(target : String)
{
return "Chopped " + target + " in half.";
}
}
interface IWeapon
{
public function hit(target:String):String;
}
Compile and run from command line with:
haxelib install unject
haxe -main Main -x Main.hx -lib unject