An IoC Container for Dart (with Autofac like API)


I enjoy throwing Darts, and have been using it quiet a bit recently. The OO nature of Dart makes it suitable for most OO design patterns. I use the inversion of control patter almost everywhere, but Dart did not have a good IoC container library that I knew of. Hence, in order to give something back to the community I wrote a lightweight IoC container based on the API of my favorite “Autofac”. The main reason for this choice was that a C# programmer who has already worked with Autofac can start using “Autodart” in a few minutes!

Below is a sample of how Autodart can be used:

class Baz{
}

class Bar{
  Baz baz;
  Bar(this.baz);
}

class Foo{
  Bar bar;
  Foo(this.bar);
}
void main(){
  var b = new AutoBuilder();
  b.register((c, p) => new Baz())
    .As("Baz")
    .singleInstance();

  b.register((c, p) => new Bar(c.resolve("Baz")))
    .As("Bar")
    .instancePerLifetimeScope();

  b.register((c, p) => new Foo(c.resolve("Bar")))
    .As("Foo"); //Default is .instancePerDependency()

  var c = b.build();

  var foo = c.resolve("Foo") as Foo;
  var foo2 = c.resolve("Foo") as Foo;

  assert(foo != foo2);
  assert(foo.bar === foo2.bar);
  assert(foo.bar.baz === foo2.bar.baz);

  /*
    Other supported API include:
    b.register(..).As(..).externallyOwned();
    c.resolveLazy("Foo") as Lazy<Foo>;
    var childScope = c.createLifetimeScope();
    c.dispose(); //Disposes all disposables in the scope
  */
}

Autodart supports the following scopes: SingeInstance (Singleton), InstancePerLifetimeScope (Nester Scopes), and InstancePerDependency.

It also defines the Disposable concept, and manages the scopes for Disposable objects.

Shortcomings: There is no auto wiring, as Dart does not yet support reflection. Also there is still no “Type” type in Dart, so string type names are used as keys. I would update the library as soon as dart adds support for reflection.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: