As I understand it, dependency injection into a base class using the ...rest
constructor parameters is dead in Aurelia 2, right? It’s a huge pain, now I have to explicitly inject all those dependencies into each derived class separately, resulting in many duplicated lines of code and wasted time. Is this the only way to go in Au 2 or is there some trick I don’t know about?
Ok, I found something that might be the easiest solution, not sure if it is correct because although this particular type of error is gone now, the app is still broken because of another migration issue and I don’t know if this is the final solution to this problem.
The solution
Use static inject
variable in the base class, no @inject
decorator:
export abstract class BaseClass {
public static readonly inject: any[] = [
IBaseDependency1,
IBaseDependency2,
];
constructor(
protected bd1?: IBaseDependency1,
public bd2?:IBaseDependency2,
) { }
Again, use static inject
variable in the derived class, no @inject
decorator here as well:
export class DerivedClass extends BaseClass {
public static readonly inject = [IDerivedDependency, ...BaseClass.inject];
constructor(
private dd:IDerivedDependency,
...rest: any[]
) {
super(...rest);
}
The trick is to use ...BaseClass.inject
when listing the required dependencies, the rest (literally, the ...rest
) is the same as in Au 1.
I would consider property injection; having a project which make heavy use of inheritance it greatly simplified our usage of constructors.
This exactly. At first, I was annoyed at the change as well, but it’s nice to have keep the derived class constructers cleaner.