Huject
Huject copied to clipboard
Passing params to new Instance
TLDR; What are the possible ways to instantiate a class that require parameters that are dynamic such as as name or something that is only know at runtime.
export class Person {
constructor(public name:string){
}
}
export class SuperHero{
constructor(public person:Person){
}
}
//other required code ... registry... etc
container.resolve(SuperHero)
I am assuming the response is going to be uses getters and setters.
However that forces me to create a public method with access to a property that i didn't really want to give access to.
I see there is a way to do it through the FactoryInterface with the make call.
Is this the only way to get something like this done?
My initial thought were that the resolve function would take ...args:any at the end and those would be appended after the resolved parameters.
Is this something that would be wanted. Is it something that could have a PR submitted for it.
ps huge fan!!
If i understood correctly you need to instantiate Person with name property by somehow calculated dynamically, correct? Yes, you need to use Factory pattern for this. Either create manual factory class (if you don't need to inject services into your Person model) or use the factory from container (if you need inject something into our Person model additionally)
Something like it:
class PersonFactory {
public createPerson(name: string) {
return new Person(name);
}
}
@ConstructorInject
class SuperHeroService {
private person: Person;
public constructor(personFactory: PersonFactory) {
this.person = personFactory.createPerson(generateSomeRandomName());
}
}
Ok that does seems to make sense