Friday, June 10, 2016

Dependency Injection with Windsor and WPF

Hi,

this month I started reading about dependency injection and found out that castle.dynamicProxy (already mentioned in earlier posts) works great with castle.windsor. This might not be surprising but nevertheless after my first project using both nuget-packages I can definitely say that using these has changed my way of work. In this project my classes are shorter, better testable and my interfaces are more proper. (About a year ago I read the book about Clean Code Development by Robert C. Martin. The book is an advertisement for TDD with some pointers about coding style and development mind sets).

One thing to mention about my project using castle.windsor: it supports even more separation of Views and ViewModels of WPF. I used a custom Activator of generic type T (derived from DefaultComponentActivator) to activate my window and asked the windsor container to resolve a singleton viewModel of type T which can be set as the datacontext (override of CreateInstance). I stored the container as a static member of a centrally available class.

So:

  • WPF-Activator<ViewModel>
  • Still consider to set the DesignViewModel in the XAML code directly
  • create a DIProvider 
  • use windsor - installers
  • remove startup-uri in app.xaml and start mainwindow with showdialog
  • prefer dependency injection over service locator pattern
  • use interfaces instead of implementations


kr, D

No comments: