Dependency-Injection

Angel uses a container hierarchy 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

  1. Future<void> myPlugin(Angel app) async {
  2. app.container.registerSingleton(SomeClass("foo"));
  3. app.container.registerSingleton<SomeAbstractClass>(MyImplClass());
  4. app.container.registerFactory((_) => SomeClass("foo"));
  5. app.container.registerLazySingleton((_) => SomeOtherClass());
  6. app.container.registerNamedSingleton('yes', Yes());
  7. }

You can also inject within a RequestContext, as each one has a controller propertythat extends from the app’s global container.

Accessing these injected properties is easy, and strongly typed:

  1. // Inject types.
  2. var todo = req.container.make<Todo>();
  3. print(todo.isComplete);
  4. // Or by name
  5. var db = await req.container.findByName<Db>('database');
  6. var collection = db.collection('pets');

In Routes and Controllers

In Angel 2.0, by wrapping a function in a call to ioc, you can automaticallyinject the dependencies of any route handler.

  1. app.get("/some/class/text", ioc((SomeClass singleton) => singleton.text)); // Always "foo"
  2. app.post("/foo", ioc((SomeClass singleton, {Foo optionalInjection}));
  3. @Expose("/my/controller")
  4. class MyController extends Controller {
  5. @Expose("/bar")
  6. // Inject classes from container, request parameters or the request/response context :)
  7. bar(SomeClass singleton, RequestContext req) => "${singleton.text} bar"; // Always "foo bar"
  8. @Expose("/baz")
  9. baz({Foo optionalInjection});
  10. }

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

  1. configureServer(Angel app) async {
  2. var db = Db("mongodb://localhost:27017/db");
  3. await db.open();
  4. app.container.registerSingleton(db);
  5. }
  6. @Expose("/users")
  7. class ApiController extends Controller {
  8. @Expose("/:id")
  9. fetchUser(String id, Db db) => db.collection("users").findOne(where.id(ObjectId.fromHexString(id)));
  10. }

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.

  1. @Expose('/controller')
  2. class MyController {
  3. final AngelAuth auth;
  4. final Db db;
  5. MyController(this.auth, this.db);
  6. @Expose('/login')
  7. login() => auth.authenticate('local');
  8. }
  9. main() async {
  10. // At some point in your application, register necessary dependencies as singletons...
  11. app.container.registerSingleton(auth);
  12. app.container.registerSingleton(db);
  13. // Create the controller with injected dependencies
  14. await app.mountController<MyController>();
  15. }

Enabling dart:mirrors or other Reflection

By default, Angel will use the EmptyReflector() to power its Container instances,which has no support for dart:mirrors, so that it can be used in contexts where Dartreflection is not available.

However, by using a different Reflector, you can use the full power of Angel’s DI system.angel init projects use the MirrorsReflector() by default.

If your application is using any sort of functionality reliant on annotations or reflection,either include the MirrorsReflector, or use a static reflector variant.

The following use cases require reflection:

  • Use of Controllers, via @Expose() or @ExposeWS()
  • Use of dependency injection into constructors, whether in controllers or plain container.make calls
  • Use of the ioc function in any route

The MirrorsReflector from package:angel_container/mirrors.dart is by far the most convenient pattern,so use it if possible.

However, the following alternatives exist:

  • Generation via package:angel_container_generator
  • Creating an instance of StaticReflector
  • Manually implementing the Reflector interface (cumbersome; not recommended)