I have experience using the Aurelia factory resolver with the @inject
class decorator:
@inject(Factory.of(Foo))
export class NeedsFoo {
foo: Foo;
constructor(fooFactory: () => Foo) {
this.foo = fooFactory(config);
}
}
The config
parameter is necessary to initialize the Foo instance, but it cannot be injected.
In larger view models, I find that @autoinject
is more convenient for managing dependencies. However, I am struggling to replicate the functionality using parameter decorators.
The documentation on resolvers is brief and lacks an example of the factory resolver property. There is a related bug reported, but understanding its usage has been challenging. Although there are discussions on Stack Overflow, they all revolve around @inject(Factory.of(...))
.
When attempting the following approach, the fooFactory object appears as an empty object {}
:
@autoinject()
export class NeedsFoo {
foo: Foo;
constructor(@factory(Foo) fooFactory) {
this.foo = fooFactory(config);
}
}
A comment in the bug discussion suggests this solution:
interface FooFactory {
new (config: any): Foo;
}
class NeedsFoo {
foo: Foo;
constructor(@factory(Foo) fooFactory: FooFactory) {
this.foo = new fooFactory(config); // error!
}
}
However, utilizing the marked line results in a
TypeError: fooFactory is not a constructor
error (as it's an empty object).
Is it possible to use parameter decorators and autoinject to inject a factory of a class in Aurelia?
edit: changed deps to config to avoid confusion regarding passing injected dependencies.
edit 2: clarification - fooFactory appears as an empty object, not undefined