views:

69

answers:

1

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 ?

A: 

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.

Mark Seemann
Currently my service locator takes in the "magic string" does a look up and instantiates a view. It then instantiates a specific ViewModel for that view and set's it to the DataContext. (Using windsor). It then calls the Load(primaryKey) function on the view model. If I was to use the data templating engine I essentially have a ContentPresenter that has it's DataContext set to the specific ViewModel I'm looking at right ? Would I then new up the ViewModel I want to transition to by supplying all of it's constructor args (IViewManagerService, etc) or would I atchitect this a different way ?
HaxElit
Yes, you can new new up the ViewModel directly, or, for greater decoupling, use an Abstract Factory. I'd tend to prefer the latter.
Mark Seemann
I'll give it a shot! Looking into the TypedFactoryFacility which seems really cool. Going to be a major rewrite but I think it's for the best. Thanks a lot, I will definitely grab your book when it's out :)
HaxElit
Yes, Abstract Factories implemented by the TypedFactoryFacility is a very cool combo :)
Mark Seemann
I just made all the changes and my code is nice and sexy now. Thanks again! BTW looking forward to getting your book.
HaxElit