0

Referencing this question: How to inject Service into class (not component)

I have a Transactions service and an Accounts service. In the transactions service, I want to use a TransactionFilter class that makes calls to the Accounts service. I think it would be nice for the TransactionFilter to have the Accounts service auto-injected. Is this a wrong way to think about things? Right now I just pass in the Accounts service whenever I create a TransactionFilter

BobtheMagicMoose
  • 1,846
  • 3
  • 16
  • 24
  • 2
    As you describe it TransactionFilter might be just another service. You inject TransactionFilter int TransactionsService and the AccountsService in the TransactionFilter. – tom van green Sep 10 '18 at 15:51
  • 1
    If you don't want to create a service out of the TransactionFilter, you can inject the accounts service manually into the class. I would say that this can be a suitable solution, dependening on your use case. – tom van green Sep 10 '18 at 15:52
  • I have a notion that a service should only have one instance. Am I correct in that thinking? I anticipate allowing distinct filters to be simultaneously maintained for different components. – BobtheMagicMoose Sep 10 '18 at 16:14
  • 2
    @BobtheMagicMoose Yes generally you'd expect there to be one instance of a service. You could have a FilterFactoryService. This would have the AccountsService injected into it and be responsible for instansiating new filters. You've then isolated the details of how the filter is created so if it changes in the future you only need to change the factory class. – matt helliwell Sep 10 '18 at 16:34
  • 1
    To add on matts comment, you can declare a service multiple times at module or component level and have multiple instances as well. But a factory is probably better in this case. – tom van green Sep 11 '18 at 07:07

0 Answers0