For example, one might want to implement something like the Command pattern. Using Injector.get
still returns the singleton instance, so that won’t work.
Here is the command class that one would want to instantiate new every time:
@Injectable()
export class EditCommand{
constructor(private someService: SomeService, private someOtherService: SomeOtherService)
{
}
}
On your component (or service) where you want to instantiate the new command instance each time you can create something like a factory with the below code:
import { Component, Injector, inject } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
})
export class MyComponent{
private injector = inject(Injector);
constructor() {
}
onSomeButtonClicked(){
const factory = Injector.create({ providers: [EditCommand], parent: this.injector });
const command = factory.get(EditCommand);
}
}