Registering the Repository in the DI Container

Right, the magic of Dependency Injection containers. Let’s start small by registering our MockRepository against the IRepository<ToDoItem> interface, and using the DI container to retrieve it in our View.

I’m going to register the interface inside the App’s constructor. This is cross-platform, so it’s the constructor inside the .NET Standard library, not the platform-specific projects.

This tells my DI container to give me an instance of my MockRepository class every time I ask for an IRepository<ToDoItem>. Since that’s exactly what I need for my View, I can change that to:

as a First step. Go and set a breakpoint where you retrieve the repo from the DI container, and you’ll see that you get an instance of a MockRepository when you ask for an IRepository<ToDoItem>.

The most important thing here is that the View is now decoupled from the MockRepository, i.e. it doesn’t decide which concrete class should be used as a repository. That means that when, later on, we want to use a real repository instead of our mockup, we only have to change the registration in our App’s constructor, rather than having to hunt down every line where we’re creating a new instance of a class that takes an IRepository as a constructor argument.

That said, this can still be improved upon – more on that in the next post.

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.


Handling Errors in the ViewModel

OK, this time round I’m going to look at what I want my ViewModel to do when things go wrong. If, for instance, the repository for my ToDoItems throws an exception.

Obviously I don’t want my app to crash if that happens, so I need to catch the possible exceptions and deal with them gracefully. In this instance I think I want to display an error message instead of my list of ToDoItems. What I’ll need for that is a) a label to display said error message and b) some way of toggling the visibility of my error message and list.

I can implement a) by simply adding a string property, and b) by binding the visibility of said elements to a boolean property in my ViewModel.

Now I only need to put my repository code in a try-catch block and handle exceptions:

Ok, right now I’m using a catch-all exception handler here, which is not great, but right now it’s all I need. I reserve the right to change my mind later.

In other news, I initialise my IsFaulted and ErrorMessage properties optimistically in my constructor, and only change them if things go horribly wrong while trying to get the data from the repository.

With that in place I can now add another test:

This time round I’m setting my repo mock up to throw an exception (asynchronously!) whenever the GetAsync method is called, and assert that my IsFaulted and ErrorMessage properties have the correct values.

…and now I think that’s enough testing for now. Time to go back to the app itself – in the next article!

Mocking Your Tests – Ha Ha!

Up until now we’ve been using a hand-rolled mock repository to supply data to our app and out unit tests. And while that’s a good first step, it gets clumsy very quickly when trying to cover different scenarios inside out unit tests. For instance, I want to write a test that asserts that the data from the repository is loaded correctly, but I also want to test that my ViewModel behaves correctly if the data retrieval from the repo fails for some reason.

Writing separate classes for each scenario is a tad over the top. fortunately there’s a simple solution: mocking frameworks. Mocking frameworks allow you to mock only the things you need for a test.

sounds a bit fuzzy, I know, so let me just show you how it works. the following code uses the Moq framework – there are others out there if you fancy. Anyway, here’s the code for my previous test, this time using Moq:

OK, let’s take a look at that. First off I’m creating a list of ToDoItems and populate it with a few dummy values. This is the list I want my mock repository to return when its GetAsync() method is called.

After that I create the mock for my IRepository<ToDoItem>. This will essentially have the same function as my MockRepository class before. Except that it’s a lot quicker to create, as you can see.

The following line is where the mocking magic happens. The Setup method of my repo mock takes an argument specifying which method to mock, followed by what that method call should return. Moq supports both synchronous and asynchronous methods now via Returns() and ReturnsAsync() respectively. In this case I’m setting the mock up to return the list of ToDoItems I created earlier whenever the GetAsync() method is called.

Finally I inject the mock for my IRepository<ToDoItem> into the constructor of my OverviewVM class. Note that I’m passing repoMock.Object, not just repoMock as a parameter. This is something that’ll likely catch you out the first few times. It certainly did with me.

After that the code remains the same. I call the LoadData method of my OverviewVM, which promptly returns the list I specified in the setup of my mock. Neat, huh?

…and in the same way we can now test how we want our OverviewVM to react if the repository fails to load the data for some reason. What that reactions should be – now that’s the topic of the next post…

Dependency Injection – Keeping Your Tests Independent

In this post I’m going to look at how to resolve the problem of how tight coupling in code causes problems for unit tests. What we have at the moment is a View Model that is tightly coupled to a repository, which makes it hard to impossible to test the View Model’s behaviour for cases like the repository throwing an exception, or being unavailable.

The way around this is by using a technique called Dependency Injection. There are many, many articles written on this subject, so I won’t go into too much depth here. I do encourage you to read up on this, because there are a few different ways of using DI.

In this case I’m going to use the most common one, which is constructor injection. Constructor injection simply means that we’re going to inject an instance of the repository through the constructor, like this:

As you can see, it’s very simple. Instead of creating the repository inside the constructor like before, we pass it as an argument. It still gets stored in the same private field, and if it’s null, we throw an exception. The exception is not necessary, of course, but in this case it makes sense because the View Model rather depends on having a valid repo to do its job.

Changing the constructor means that now the project will no longer compile, of course, so we need to go in and change a few more things.

First off, since we’re looking at unit testing, let’s change the test setup:

While this is still using the old mock repository, it’s now possible to use different repos in further tests. I’m also going to create a second test to test that passing a null argument will throw the correct exception:

The final step is to change the construction of the OverviewVM in the constructor of the OverviewPage class. For now let’s just inject null. It means that the app won’t run because of the exception that will get thrown, but it will compile so that you can run the tests.

Well, that’s it for now. In the next post I’m going to create more tests and introduce you to mocking frameworks – fun times ahead!

Unit Testing – Keeping Your Code Running

Now that we have code that’s starting to resemble something usable, it’s high time to put in some Unit Tests. I’m using NUnit as my testing framework, but feel free to choose something else. First off, I like to keep my tests organised, so I usually create a folder tree in my solution. In this case I start by adding the following folder structure: Testing -> GoalBuddy for the tests of my common code. Inside that folder I then create a new NUnit3 unit test project.

Two things to mention here: after you install the NUnit test runner and templates, you can create four different kinds of test projects: Android, iOS and UWP, located under “Cross-Platform”, and a platform independent one, located under “Test”. Choose the last one for unit testing your common code.

The other thing to do is to make sure your unit test project is compatible with .NET Standard. Out of the box, your common code will be in a .NET Standard 2.0 library, so your test project needs to reference .NET 4.6 or higher.

Now add a reference to the project that holds your common code to your unit test project, build your solution and run the default test as a sanity check.

Next, let’s add a test that checks that data actually gets loaded into the ViewModel:

Now you can see that, although the test should run without problems, this is already a bit weird. I assert that the ViewModel should have 3 ToDoItems, but I never arrange for that. Right now that’s hard coded into the constructor of my ViewModel, which is really bad for testing. What if I want to add another test that tests for the correct behaviour if my repository throws an exception?

Sure, I could change my repository to do that, but then it will always do that, of course, but that would then cause the test I just wrote to fail. Not great. And that’s where Dependency Injection comes in – more on that in my next post!

Asynchronous Loading of Data – a Better Way

When last we left off, we were loading the data for the ViewModel inside its constructor – a bad idea, because the data loading is done asynchronously, and constructors can’t be made async. So we need to find a better way to do that.

First off I want to factor the process of loading the data out to its own method inside my OverviewVM class:

With this public method I’ve got more options on handling the data. So the question is: do I really need to load the data right when my View Model is constructed? Actually, no. I don’t need the data until my View appears – and the OnAppearing() method can be made async to accommodate the asynchronous nature of data loading.

Because I need a reference to my View Model in OnAppearing(), I’m storing it in a field for now. Later on, when we get to decoupling our classes, that’s going to be done a better way, but for now this will do the job.

Except that there’s a little problem now. Because the data we’re binding to is not already in place when the page appears, our list of ToDo’s is empty. We need to explicitly tell our View that our collection of ToDoItems has changed.

I could do this by making my ViewModel implement the INotifyPropertyChanged interface – but fortunately MVVMLight already has a base class in place that will handle all of that for me. All I need to do is to make my View Model inherit from ViewModelBase and use ViewModelBase’s Set method, which handles both the assignment and notification for me.

The resulting View Model now looks like this:

So, another hurdle jumped. The code is slowly starting to look better, but still suffers from tight coupling. More on this next!

Repositories – Getting the Data to the ViewModel

Right now the ViewModel is pretty hideous. It shouldn’t be responsible for fetching the data, much less creating it – that’s a clear violation of the Single Responsibility Principle and all round Bad Idea (TM). So let’s make that the responsibility of a repository.

I have a go-to repository interface that I use as a starting point:

IEntity is there purely to make sure that the class in the repository has an Id field. Feel free to leave it out if you don’t need it, but it’s useful if you want to have a unique identifier for retrieving/updating entities in your repository.

For use with SQLite, I use IEntity to create a primary key on the Id:

…and then I make my ToDoItem class inherit from it.

Now my ToDoItem class fulfils all the requirements for use in a repository that implements IRepository<T>. Eventually I want that to be a repository that uses SQLite, but for now I’m going to use a bare-bones mock-up with some hard-coded data.

I’ll use this later in unit testing, so creating it is not actually a waste of time.

and now, finally, I can change my ViewModel to use this repository:

Now, looking at this, the ViewModel is still in a world of wrong. In fact, it’s so wrong that almost every line in it needs to be changed. We have tight coupling, we are blocking the UI thread because you can’t use ‘await’ in a constructor, we’re using a mock repository and an unsuitable collection, but fear not – all this will be addressed over the course of the next few posts…

How to Start Writing a Simple Xamarin App

Welcome to my blog! This entry is the first in a series detailing the process of developing a non-trivial Xamarin.Forms app from start to finish.

This series of blog posts assumes that you are familiar with at least the concepts of MVVM and Dependency Injection, that you know XAML and XAML bindings, how to create a Xamarin.Forms project and that you know how to install NuGet packages into that project.

I will be working with a blank Xamarin.Forms project, using a .NET Standard library for code sharing if you want to follow along. This is the new template that Visual Studio 2017 offers for Cross-Platform development – if you still see the old PCL approach you may have to upgrade Visual Studio to the latest version.

The first thing I do with a new project is to add the NuGet packages for MVVM and SQLite. I use MvvmLightLibsStd10 and sqlite-net-pcl (not to be confused with SQLite.Net-PCL!) MvvmLightLibsStd10 is for use in .NET Standard projects; if you’re using a PCL library, install MVVMLightLibs instead.

At this point I usually run my new application, just to make sure everything’s set up OK.

Next I add folders: a “Views”, a “ViewModels” and a “Models” folder to support my MVVM structure. I also delete MainPage.xaml and MainPage.xaml.cs. I want to keep all my pages in my views folder, and creating a new page there is quicker and easier than to change the namespace of an existing one. Plus, I really don’t like the name “MainPage” – I may decide later on that a different page should be the first to be presented to the user at startup, and then where would I be? I prefer my pages to have names that describe their purpose.

With all that reorganisation out of the way, let’s get cracking with the code. This series of articles is going to do – a todo list! Because that’s something that nobody has ever thought of before. Yay.

OK, yes, I know it’s been done to death, but it’s got two advantages. First, you’ve probably come across a very simple version of this kind of app in another tutorial. But more importantly, this is an app that can be expanded to be quite complex, and gives me the opportunity to show you not only some Xamarin.Forms code, but also how to code for maintainability and extensibility.

So, let’s start with the simplest possible scenario: a single-page app that displays a list of tasks, just to get something to look at. For this we’ll need a View, a Model and a ViewModel to bind them together.

Let’s start with the Model, which is really simple at this point. Just a property to hold the title of the ToDo item, a property to hold a more detailed description, and a property to hold the current state of the task.

I’ m using an enumerable rather than a Boolean to store the state. I can see that I may want more than two possible states in the future, so I’m allowing for that possibility. It’s not strictly speaking necessary, as SQLite is very forgiving with regards to types – a column is not locked to a datatype, like in SQL server – but I want to keep this consistent.

Next, the ViewModel. I’m going to keep this super simple for now – just a hardcoded list of ToDoItems. If this scares you, don’t worry. I’ll remove the hideousness of this in the next article…

Finally, the view – create a XAML Content Page and call it “OverviewPage”. On this page I want a list that displays todo items and whether or not they’re done. Unfortunately there is no pre-fab ListView cell that displays text and a checkbox, so for the sake of keeping this article at a reasonable length, I’m going to forget about the checkbox for now and use a plain TextCell:

And, of course, we need to make the OverviewPage the new start page when the App is instantiated.

So, a quick and dirty (but working) app. In dire need of improvement. Up next: creating a ViewModel that won’t make your boss head-slap you.