Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Passing params to new Instance #10

Open
shavyg2 opened this issue Jul 6, 2017 · 3 comments
Open

Passing params to new Instance #10

shavyg2 opened this issue Jul 6, 2017 · 3 comments

Comments

@shavyg2
Copy link

shavyg2 commented Jul 6, 2017

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.

@shavyg2
Copy link
Author

shavyg2 commented Jul 6, 2017

ps huge fan!!

@asvetliakov
Copy link
Owner

asvetliakov commented Jul 6, 2017

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());
  }
}

@shavyg2
Copy link
Author

shavyg2 commented Jul 7, 2017

Ok that does seems to make sense

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants