The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

Vitalii (1) [Avatar] Offline
I have a question to ask about Service Locator.
I have a piece of code listening to messages coming from the queue, gets the message type T and uses an IServiceProvider to create a scope and dynamically resolve a IMessageHandler<T> and invoke it. Is such usage considered a Service Locator? I would argue that my code is more a piece of infrastructure, similar to what MVC does to instantiate a controller for each request.

If it's still a wrong way to use it, how would you suggest to refactor this? The only thing coming to mind is that I could accept a dictionary of <Type, Func<IMessageHandler<T>>> through constructor injection and that dictionary would be configurable in Composition Root.
Bu that seems an overkill...

Thanks for any suggestions!
Steven van Deursen (43) [Avatar] Offline

As we state in chapter 5, any use of a DI Container, inside the Composition Root is good use, and does not imply the Service Locator anti-pattern. So as long as this piece of infrastructure is part of your Composition Root, it is fine. If it's not part of your Composition Root, consider moving it into the Composition Root.

This doesn't mean that you should move all the messaging infrastructure code into the Composition Root, but just the part that requires knowledge of the DI Container or an abstraction over it.