cork

Build Status

Yet another dependency injection framework for Dart, built based on Dagger.

Example:

import 'package:cork/cork.dart';

// "Inject" means that something can be created by an Injector.
@Inject()
class Foo {}

class CustomFooImpl implements Foo {}

// "Module" is a collection of Inject-ables, and other Modules.
// It can also provide custom factory functions.
@Module(const [Foo])
class FooModule {
  // Instead of using the default factory for Foo, use this function.
  @Provide(Foo)
  static Foo getFoo() => new CustomFooImpl();
}

Cork is built with static analysis and tree-shaking in mind, but is currently only a prototype. There are three planned ways to use Cork in your application:

Dynamic mode (using dart:mirrors)

Suitable for use in the Dart VM (e.g. server-side), or within Dartium only.

import 'package:cork/dynamic.dart';

// Assume same file as above.
import 'foo.dart';

void main() {
  var injector = createInjector(FooModule);
  var foo = injector.get(Foo);
  assert(foo.runtimeType == CustomFooImpl)
}

Simple codegen mode (using hand-written bindings):

import 'package:cork/cork.dart';

// This is currently *not* recommended, and for experimental use only.
import 'package:cork/src/binding.dart';

import 'foo.dart';

void main() {
  var bindings = [
    new Binding(Foo, new Provider(() => new CustomFooImpl()))
  ];
  
  var injector = new Injector(bindings);
  var foo = injector.get(Foo);
  assert(foo.runtimeType == CustomFooImpl);
}

Simple codegen mode (using the binding generator):

Experimental: Still in development.

var foo = Uri.parse('package:cork/testing/library/foo.dart');

// The dart file generated.
var generator = new StaticBindingGenerator();
var result = await generator.generate(foo);

Static class mode:

Experimental: Still in development.

Generates a class called $GeneratedClass:

var foo = Uri.parse('package:cork/testing/library/foo.dart');

// The dart file generated.
var generator = new StaticClassGenerator();
var result = await generator.generate(foo);

The output looks something like this:

import 'package:cork/testing/library/foo.dart' as import_1;

class $GeneratedInjector {
  import_1.Foo _1;
  import_1.Foo get1() {
    if (_1 == null) {
      _1 = new import_1.Foo();
    }
    return _1;
  }
}

Libraries

cork.dynamic
cork.interface

Import this library in order to get the abstract classes and annotations for the library. Useful to use another implementation without depending on any implementation code within.

cork.testing.integration.library_spec
cork.testing.library.foo_imported
cork.testing.library.integration_spec
cork_static_bindings
cork_static_bindings
cork_static_class
cork_static_class
foo