Vitalii (1) [Avatar] Offline
#1
Hi!
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 (40) [Avatar] Offline
#2
Hi,

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.