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.
// Inject typesreq.inject(Todo, someTodoInstanceSingleton);// Or by namereq.inject('database', await databaseProvider.connect('proto://conn-string'));// Inject into *every* requestapp.inject('foo', bar);
As you can imagine, this is very useful for managing things such as database connections.
configureServer(Angel app) async {var db =newDb("mongodb://localhost:27017/db");await db.open(); app.container.singleton(db);}@Expose("/users")classApiControllerextendsController {@Expose("/:id")fetchUser(String id, Db db) => db.collection("users").findOne(where.id(newObjectId.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.
@Expose('/controller')classMyController {finalAngelAuth auth;finalDb db;MyController(this.auth, this.db);@Expose('/login')login() => auth.authenticate('local');}main() async {// At some point in your application, register necessary dependencies as singletons... app.container.singleton(auth); app.container.singleton(db);// Create the controller with injected dependenciesawait app.configure(app.container.make(MyController));}