14

I'm pretty new to Aurelia (only been using it a few days) and I love it!

I know how to make a service with Aurelia, but how can I make that service a singleton that I can then share data with between multiple ViewModels?

Thanks

  • 2
    @manetsus what do you mean? I'm asking how to create a singleton service in Aurelia instead of an injected instance into my ViewModel. I'm not sure if I can get anymore specific :-( – Michael Huntington Jul 18 '15 at 00:11
  • Stackoverflow is a platform where you should represent your problem with showing some effort you made behind it. You have to google it before posting a question. Represent where specifically you are stacked! – Enamul Hassan Jul 18 '15 at 00:17
  • @manetsus The effort I put behind it was finding out Aurelia injects instances of objects into ViewModels... The framework is just a few months old so there's not a lot of information on Google... I've done the search already. I signed up for StackOverflow just for this one question. – Michael Huntington Jul 18 '15 at 00:24
  • Your effort report should be added to your question, so that experts know that you did some effort behind it, I got your question as a reviewer so that you could post improved question, Thanks. – Enamul Hassan Jul 18 '15 at 00:32
  • 7
    @manetsus I imagine you got this question as a review item not because it needed improving but because Michael is new. The question seems fine to me. Worded well and specific. The only suggestion I would have offered would have been to show the code he is using to inject an instance. This would allow an answerer to easily provide a suggestion. – 4imble Jul 23 '15 at 09:48

2 Answers2

24

Just inject it

By default, the DI container assumes that everything is a singleton instance; one instance for the app. However, you can use a registration decorator to change this.

Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467
JamesCarters
  • 771
  • 7
  • 12
5

So I realized I was thinking about this too hard. I was trying to depend on the framework (Aurelia) to do all the work, but actually it was a simple ES6 class change that makes it an instance.

let instance = null;

export class SingletonService {

 constructor() {
  if(!instance) {
   instance = this;
  }

  return instance;
 }
}