Handling Dependency Injection in the View

OK, after all that testing, let’s head back to the app itself, where we have introduced a bit of a problem when we changed the View Model to use Dependency Injection via the constructor.

Just to recap: Here is the current constructor for our ViewModel, where we’re injecting our repository (just the relevant bits):

… and here is our current View:

As it stands, the ViewModel is going to throw an ArgumentNullException, so we need to do something about that.

Now, the quick and dirty way to handle this would be to create the repository in the constructor for our View and inject it right there, but that violates the principles of MVVM big time. The View should have no knowledge of, well, pretty much anything except for the ViewModel (ideally).

Furthermore, creating an instance of the ViewModel creates tight coupling. In my opinion, since it’s between two classes that are very closely related, that might be acceptable. Still, loose coupling would be preferable.

A popular solution to this problem is to use a Dependency Injection Container, and, as luck would have it, there’s a very simple one, called SimpleIoc, baked into the MVVMLight package.

Again, there’s tons to read about DI containers, and I’d encourage you to do so. For now, let’s stick to the very basics: a DI container allows you to register a class for retrieval later, BUT it also does allow you to register a class against an interface and, by magic, will substitute those interfaces for the registered classes when found in a constructor.

Yes, that sounds complicated, but in practice it really isn’t. Over the next few posts I’m going to walk you through the process, step-by-step.

 

Leave a Reply

Your email address will not be published. Required fields are marked *