1

I'm trying to apply DI to my WPF application (with MVVM). I would like to adhere to an onion architecture, and as such, my model has an IRepository interface which is injected via an IoC container into the application from its composition root.

There are countless sources like this SO answer and this post on wpftutorial.net that talk about DI with WPF but which show the repository being injected into the view model. Doing that doesn't seem right to me. The view model, in my mind, should not be concerned (i.e. should not know about) the repository.

Is there a way to design my application so it properly adheres to the onion architecture and does not involve the presentation layer in the repository dependency injection (inasmuch as that's possible, given that the composition root must be in the top-level/executable where the views reside)?

Community
  • 1
  • 1
rory.ap
  • 34,009
  • 10
  • 83
  • 174
  • 1
    My preference is to wrap repositories into a higher abstractions that encapsulate use cases and queries. You can inject these abstractions into your view model. Take a look at [this](https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91) and [this](https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92) for instance. – Steven Oct 13 '16 at 13:18
  • I'm also not a fan of mixing concerns, but I have solved it by introducing yet another level of abstraction that is a ViewModelFactory which does all the work to constitute the given viewmodel. Since I delegate that task to this factory it can receive the repository contract interface (or IQueryHandlers as Steven mentioned) in its constructor, and work with it later. – kayess Dec 08 '16 at 09:44

1 Answers1

1

One way would be to define your repository using an interface and then using unity you can interject the correct implementation of the repository interface.

The link here should get you started on using unity:

https://msdn.microsoft.com/en-us/library/dn223671(v=pandp.30).aspx

Update:
By looking at the onion method on your link, I would suggest interjecting your repository in the Business/Application Logic layer. And make the calls to these methods form the view model as needed.

  • Thanks for your answer. I may not have been clear; I thought that the fact that I'm using DI implied that I'm using an interface for the repository. I'm already using an IoC container (Ninject). My question isn't about *what* to inject, it's *where* to inject. I don't want to inject repository -- interface or otherwise -- at the presentation layer. – rory.ap Oct 13 '16 at 13:25