Dependency Injection

Angel uses Emil Persson's Container for DI. Dependency injection makes it easier to build applications with multiple moving parts, because logic can be contained in one location and reused at another place in your application.

Adding a Singleton

class MyPlugin extends AngelPlugin {
  call(Angel app) async {
    app.container.singleton(new SomeClass("foo"));

class SomeClass {
  String text;

You can also inject within a RequestContext.

// Inject types
req.inject(Todo, someTodoInstanceSingleton);

// Or by name
req.inject('database', await databaseProvider.connect('proto://conn-string'));

// Inject into *every* request
app.inject('foo', bar);

In Routes and Controllers

app.get("/some/class/text", (SomeClass singleton) => singleton.text); // Always "foo""/foo", (SomeClass singleton, {Foo optionalInjection});

class MyController extends Controller {

  // Inject classes from container, request parameters or the request/response context :)
  bar(SomeClass singleton, RequestContext req) => "${singleton.text} bar"; // Always "foo bar"

  baz({Foo optionalInjection});

As you can imagine, this is very useful for managing things such as database connections.

configureServer(Angel app) async {
  var db = new Db("mongodb://localhost:27017/db");

class ApiController extends Controller {
  fetchUser(String id, Db db) => db.collection("users").findOne( ObjectId.fromHexString(id)));

Dependency-Injected Controllers

Controllers have dependencies injected without any additional configuration by you. However, you might want to inject dependencies into the constructor of your controller.

class MyController {
  final AngelAuth auth;
  final Db db;

  MyController(this.auth, this.db);

  login() => auth.authenticate('local');

main() async {
  // At some point in your application, register necessary dependencies as singletons...

  // Create the controller with injected dependencies
  await app.configure(app.container.make(MyController));

Last updated