Dependency Injection: create a new instance of the injectable on each call. #40262
Description
🚀 feature request
Relevant Package
Angular core, IVY, DI
Description
I would like to have in my application some kind of 'commands/actions' that suppose to execute some logic and hold the state.
Example usage:
Users can execute different commands from the component and also undo.
Each command should store some state in order to perform some action and undo the action.
I would like to have something like:
@Injectable({
providedIn: "transient",
})
export class Command1{
constructor(logicExecutor:Service){ }
uniqueCommandState = ''
do(commandState:string){
this.uniqueCommandState = commandState;
// Call here few services. to perform BL
this.logicExecutor.do_something();
}
}
// Then I can call it from the component:
@Component({
selector: "app-context-menu",
templateUrl: "./context-menu.component.html",
styleUrls: ["./context-menu.component.scss"]
})
export class ContextMenuComponent
constructor(private injector: Injector) {}
buttonClick() {
// Use angular DI to help instantiate command with various services:
const uniqueCommand = injector.get(Command1);
uniqueCommand.do('id');
// I would expect the each command will be unique, stored to be handled later. Ex: undo
}
}
Describe the solution you'd like
I would like to have a mode for the Injectable attribute to allow create new instance on each request.
Another option is some kind of flag to resolve any class constructor arguments with the registered services:
const uniqueCommand = injector.get(Command1, ... InjectFlags.ResolveInstanse)
Describe alternatives you've considered
Remove the created instance from a cache:
const result = this.injector.get(Command1);
(this.injector as any)?.records?.delete(Command1);
So far, there are some limitations.
See how it's works in .NET (transient state):

Formed in 2009, the Archive Team (not to be confused with the archive.org Archive-It Team) is a rogue archivist collective dedicated to saving copies of rapidly dying or deleted websites for the sake of history and digital heritage. The group is 100% composed of volunteers and interested parties, and has expanded into a large amount of related projects for saving online and digital history.
