Injectable class

Compile-time metadata that marks a class Type or Function for injection.

The @Injectable() annotation has three valid uses:

  1. On a class Type
  2. On a top-level Function
  3. On a static class method

Use #1: A class Type

The class must be one of the following:

  • non-abstract with a public or default constructor
  • abstract but with a factory constructor

A class annotated with @Injectable() can have only a single constructor or the default constructor. The DI framework resolves the dependencies and invokes the constructor with the resolved values.

Example

// Use the default constructor to create a new instance of MyService.
@Injectable()
class MyService {}

// Use the defined constructor to create a new instance of MyService.
//
// Each positional argument is treated as a dependency to be resolved.
@Injectable()
class MyService {
  MyService(Dependency1 d1, Dependency2 d2)
}

// Use the factory constructor to create a new instance of MyServiceImpl.
@Injectable()
abstract class MyService {
  factory MyService() => new MyServiceImpl();
}

Use #2: A top-level Function

The Injectable() annotation works with top-level functions when used with useFactory.

Example

// Could be put anywhere DI providers are allowed.
const Provide(MyService, useFactory: createMyService);

// A `Provide` may now use `createMyService` via `useFactory`.
@Injectable()
MyService createMyService(Dependency1 d1, Dependency2 d2) => ...

Use #3: A static class method

This works the same way as with top-level functions.

Annotations
  • @Target({TargetKind.classType, TargetKind.function, TargetKind.method})

Constructors

Injectable()
const

Properties

hashCode int
The hash code for this object.
no setterinherited
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited