close
The Wayback Machine - https://web.archive.org/web/20250124193054/https://github.com/angular/angular/issues/40262
Skip to content

Dependency Injection: create a new instance of the injectable on each call. #40262

Closed
@ievgennaida

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):

https://stackoverflow.com/questions/38138100/addtransient-addscoped-and-addsingleton-services-differences

Metadata

Assignees

No one assigned

    Labels

    area: coreIssues related to the framework runtimecore: difeatureIssue that requests a new featurefeature: insufficient votesLabel to add when the not a sufficient number of votes or comments from unique authorsfeature: votes requiredFeature request which is currently still in the voting phase

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions