Permalink
Browse files

initial commit

  • Loading branch information...
0 parents commit c22b6690e73f50217934331f99d79fe2cc90d626 @jasonmay committed Dec 15, 2010
Showing with 122 additions and 0 deletions.
  1. +2 −0 .gitignore
  2. +9 −0 lib/IoC.pm6
  3. +15 −0 lib/IoC/BlockInjection.pm6
  4. +28 −0 lib/IoC/ConstructorInjection.pm6
  5. +15 −0 lib/IoC/Container.pm6
  6. +7 −0 lib/IoC/Literal.pm6
  7. +7 −0 lib/IoC/Service.pm6
  8. +39 −0 t/01-basic.t
@@ -0,0 +1,2 @@
+Makefile
+blib
@@ -0,0 +1,9 @@
+module IoC;
+
+use IoC::Container;
+
+my %cc;
+
+sub container($pair) is export {
+ # XXX
+}
@@ -0,0 +1,15 @@
+use IoC::Service;
+class IoC::BlockInjection does IoC::Service {
+ has Sub $.block;
+ has $.class;
+
+ method get {
+ if ($!lifecycle eq 'Singleton') {
+ return (
+ $!instance ||= $!block.();
+ );
+ }
+
+ return $!block.();
+ }
+};
@@ -0,0 +1,28 @@
+use IoC::Service;
+class IoC::ConstructorInjection does IoC::Service {
+ has Str $.class;
+ has %.dependencies = ();
+ has %.parameters;
+ has $.container is rw;
+
+ method get {
+ if ($!lifecycle eq 'Singleton') {
+ return (
+ $!instance ||= self.build-instance();
+ );
+ }
+
+ return self.build-instance();
+ }
+
+ method build-instance {
+ my %params;
+
+ for %!dependencies.pairs -> $pair {
+ %params{$pair.key} = $!container.fetch($pair.value).get();
+ };
+
+ return $!class.new(|%params);
+ }
+};
+
@@ -0,0 +1,15 @@
+class IoC::Container {
+ has %!services = ();
+
+ method add-service($name, $service) {
+ if $service.^can('container') {
+ $service.container = self;
+ }
+ $service.name = $name;
+ %!services{$name} = $service;
+ }
+
+ method fetch($service-name) {
+ return %!services{$service-name};
+ }
+};
@@ -0,0 +1,7 @@
+use IoC::Service;
+
+class IoC::Literal does IoC::Service {
+ has $.value;
+
+ method get { return self.value }
+};
@@ -0,0 +1,7 @@
+role IoC::Service {
+ has Str $.name is rw;
+ has Str $!lifecycle;
+
+ # for singletons
+ has Any $!instance;
+};
@@ -0,0 +1,39 @@
+BEGIN { @*INC.push('lib') };
+
+use IoC::Container;
+use IoC::ConstructorInjection;
+use IoC::BlockInjection;
+use Test;
+
+plan 4;
+
+my $c = IoC::Container.new();
+
+class Bar {};
+class Foo { has Bar $.bar; };
+
+$c.add-service(
+ 'foo', IoC::ConstructorInjection.new(
+ :class('Foo'),
+ :lifecycle('Singleton'),
+ :dependencies({
+ 'bar' => 'bar',
+ }),
+ )
+);
+
+$c.add-service(
+ 'bar', IoC::BlockInjection.new(
+ :class('Bar'),
+ :lifecycle('Singleton'),
+ :block(sub {
+ return Bar.new;
+ }),
+ )
+);
+
+ok($c.fetch('foo').get);
+ok($c.fetch('bar').get);
+
+ok($c.fetch('foo').get.bar);
+is($c.fetch('foo').get.bar, $c.fetch('bar').get);

0 comments on commit c22b669

Please sign in to comment.