wpfdependency-injectionservice-locator

WPF DI Service Locator


So I'm looking for some clarification how it would be possible to remove the service locator from my application.

I have a ViewManagerService that is responsible for knowing which view is active, which views are open and creating a new view.

Currently my ViewModels get an IViewManagerService injected into them via constructor injection. These ViewModels expose ICommands that when invoked can then make a call to

viewManager.Transition("MyCoolView", somePrimaryKey);

The ViewManagerService then uses a service locator to look up and instantiate a new view with the key "MyCoolView". The reason for using a key string is so I can decouple the View from the ViewModels. I would like to keep the ViewManagerService generic enough so I can use it for other apps, so I don't want it to depend on a specific IAbstractFactory interface.

Any tips/suggestions ?


Solution

  • You can get rid of magic strings completely by using WPF's data templating engine. The best way to do that is to use the MVVM pattern. It's orthogonal to DI, but a great enabler.

    Once you've made that transition, you can have a pure DI architecture without having to rely on the Service Locator anti-pattern.