0

I'm trying to set up a multi-tenant application where the back-end talks to multiple environments of the same service based on the request locale. Because these environments each have their own client, I currently have a ClientProvider class that returns the correct client for each locale. However, that leaves me with ClientProvider.ProvideForLocale() calls everywhere, which are kind of bloating the code IMO.

Instead, I'd like to inject a request-scoped client based on the locale provided in the request using the DI framework, but I can't seem to figure out how to do it. Is this even possible?

Sander
  • 1,183
  • 12
  • 27
  • Have you considered injecting factory that will provide locale-specific instances? – yoger Jul 08 '19 at 13:06
  • The `ClientProvider` is the factory, right? Apart from naming, I don't think that would make any difference, or maybe I don't fully understand what you mean. – Sander Jul 08 '19 at 14:44

1 Answers1

0

The whole purpose of dependency injection is to have these dependencies injected into the constructor of the object. I'm assuming your application is an MVC based API. For an MVC application, that constructor is called and all dependencies injected before any requests are processed.

If you want to reduce code bloat, Look into the OnActionExecuting event. I think it will do what you want.

You can see a previous Stack Overflow post here: Execute code before/after every controller action

  • Though, if I understood it correctly, a scoped dependency is instantiated for every request, right? – Sander Jul 08 '19 at 14:43
  • Every dependency is instantiated on every request... In an MVC application, the controller itself is instantiated on every request as well. – douglas.kirschman Jul 09 '19 at 15:58