Xamarin MVVM Architecture – Part 2: What Goes Where?

LinkedInTwitterGoogle+FacebookRedditEmail

Welcome!

In the previous post of my series on Xamarin MVVM Architecture, I introduced some of the many pros of committing some time upfront to properly architecting your Xamarin projects. In this post, we’ll dive deeper into some techniques you can (and should!) use to make your life as an architect much easier.

 

What goes where?

The first thing we’ll cover is a quick look at where I think you should place your various elements. To do so, let’s take a closer look at the some projects. Now, some of these won’t be present if your project, but for the most part, it should look pretty standard for a network connected mobile application. Note that they are named oddly, to get them in logical order in the Solution explorer – don’t do this normally.

 

 

To better understand what each of the layer’s responsibilities are, at a high level, we’ll follow the path of a common procedure – logging in a user. Following are the common steps you may take, along with which layer they are occurring in.

 

Direction Layer Step
Forms  UI issues a LoginCommand to a ViewModel.
Core  ViewModel allows LoginCommand to Execute, passes form information downwards, to Data Access Object (DAO), requesting a login.
Data  DAO receives the user’s credentials, passes them downwards, to the Network Access Object (NAO), requesting a login request.
Net  NAO POSTs the credentials to some server, and if all goes well, receives some JSON back. This JSON is passed upwards to the DAO, as a raw string.
Data  DAO has been await-ing the JSON string, and upon receipt, deserializes it into one of its known Models. This Model may be passed upwards, back to our ViewModel. Regardless, DAO lets the VM know that a login has completed.
Core The ViewModel’s wait is over, and it now knows that a login has completed. It requests that something capable of displaying a success dialog does so.
Forms  Some DialogService triggers an successful login alert.

 

This should sound pretty familiar to anyone who has ever setup a login in an application before, regardless of whether or not you’re using Xamarin. Now we’ll take a look at a few interesting stops along the path we took to get this action completed.

 

Don’t look up!

Notice how each layer only called into the layers “below” it. Forms requested that the Core, which contains the ViewModels, perform the login. The ViewModel may know about the Models, but they are below it. This downward dependency setup allows us to better adjust to changes when need be, by not having bi-directional requirements. It also allows for each layer to be as decoupled as it possibly can be, which lends itself perfectly to the maximum cross platform reuse we’re aiming for.

Observe for a minute the route we took to turn the server response JSON into an in memory Model, because this is a prime opportunity to accidentally couple. We have the NAO (Network Access Object) returning raw JSON, as a String. This is really good. If we wanted to do the deserialization in this layer, and have the NAO call return a completed model, the Net layer would now have an upward dependency on the Data layer’s models. That is bad.

One of the reasons that that would be very bad is that it directly violates the Separation of Concerns (SoC) principal. This principal basically states that each unit of code should only do one thing. It makes sense for our Net layer to make a request to the server, but does it really make sense for it to deserialize an object? What if the process of deserialization has to do some other stuff, like apply business rules and establish in-memory relationships? It should be quite clear that these things have nothing to do with performing a network request, so you’d do well to keep things broken apart.

 

Third party dependencies.

Note also in our example that we’re working with JSON. In the .NET world, that means you’re probably using Newtonsoft’s Json.NET. If we do our deserialization in the Net layer, now there is an external dependency that doesn’t make a lot of sense. Especially since the Data layer probably is also using Json.NET in various ways.

 

Breaking rules.

One of the hardest (or funnest) parts of software architecture is that you are always capable of breaking the rules. If you check out the Xamarin Azure Component, you’ll see that its API returns model objects. Now, when you use Azure, you’ll probably just omit the Net project, and have it function as a Data layer dependency. Since they use a nice templated approach to returning their objects, I think this is totally acceptable. They technically don’t have any hard upward dependencies, as they’re capable of returning any type that their caller requests:

 

MobileServiceClient client = new MobileServiceClient("AppUrl", "AppKey"); 

IMobileServiceTable<TodoItem> todoTable = client.GetTable<TodoItem>();
    
List<TodoItem> items = await todoTable.Where(i=>i.Complete==true).ToListAsync();

 

So, if you’re using Azure, expect this behavior. And, if you’re not, and feel the benefits are worth the extra architecture, go for it! Just always stay cognizant of which project depends on which layer.

 

Depend upwards, indirectly.

To wrap things up, I’d like to briefly go over how you can look upwards correctly, when you must.

The best example for this in my opinion, is that of persistence. Most apps need to persist stuff, and most apps end up using SQLite in one way or another. And, since SQLite is pretty much everywhere, that’s a great choice to make. Now, imagine, in our example, we’ve gone down to the Net layer, received some JSON, and are currently in the Data layer. We’ve deserialized the string into a proper Model, and are prepared to return it upward. But first, we want to store the logged in user to disk. Normally we’d persist their session or OAuth token, but for now assume we’ll just persist the whole user.

This seems easy enough to do, we just ask our SQLite connection to write out some table data. But.. where does the connection come from? Therein lies our problem. Each platform has different implementation expectations for working manually with databases. They have different directories, some are sandboxed, and so on. So if each platform is providing their own implementation (they must), and a layer many levels beneath them needs to access it, what can we do?

Well, the short answer is, we can use Inversion of Control (IoC). By using an IoC “container”, we get a middleman, whom the producers can register implementations of interfaces with, and consumers can access said implementations via. At the very core, it is essentially a static dictionary mapping interfaces to implementations of said interfaces.

The way that Xamarin documents doing this is using their Dependency attribute and the static DependencyService method, Get<T>(), as is illustrated in this tutorial.

In our case, we would simply have an ISQLite interface, which each platform implements and registers. Then, in the Data layer, we’d access the platform specific instance via DependencyService.Get<ISQLite>();

You can see this very example in their sample codebase, here, here, here, and here.

 

Don’t use Xamarin.Forms.Dependency!

So, now that we just learned what DependencyService is, know that I strongly suggest you don’t use it! I promise I’m not going crazy here, let us again think about our layer dependencies now. If we use DependencyService to access our database connection, or whatever we’re doing, we can churn out some nice iOS, Android, WP, etc apps. But, what about when someone wants to drop a WPF client on top of our super-reusable code base? Or a Xamarin.Mac app? Well.. it turns out our Data layer actually is now depending on the Xamarin.Forms library, and that is a really bad upward dependency, and one that can’t be replicated on non-Xamarin.Forms client applications.

So, instead, I recommend using a “neutral” IoC container. And, I also happen to have one I really like – MVVMLight. This super lean toolkit is just incredible. And, it’s available on pretty much all platforms.

Using it is really straightforward. Rather than using the Dependency attribute, you just have to manually register the implementation you’d like with it, like so:

 

SimpleIoc.Default.Register<ISQLite, SQLite_iOS>();

 

This actually is a good thing, as the Register method provides a few great overloads. Then, to access it in the Data layer, or whichever layer, just use SimpleIoc.Default.GetInstance<T>(). Or, use the ServiceLocator class that Microsoft provides, and MVVMLight depends on. By doing this, you now have all of the benefits that inversion of control affords, with none of the unnecessary dependencies.

 

Wrapping up.

This is some pretty cool stuff, I think. In addition to the techniques and tools I’ve shown, I hope it also stands out that every single dependency, decision, separation, and so on must be thoroughly considered. Only with this stringent architectural approach can you maximize your project’s current and future reuse capabilities.

In a future post we’ll explore further what MVVMLight brings to the table. It has many cool things in its small footprint – dependency injection, lazy IoC options, IoC caching options, navigation and dialog service interfaces, and other goodies. If you can’t wait, I highly recommend checking out this Pluralsight course on it, which MVVMLight’s creator, Laurent Bugnion, has put together.

As always, I’d just like to thank all of you who’ve thought through this with me, and welcome all comments below.

LinkedInTwitterGoogle+FacebookRedditEmail

Xamarin MVVM Architecture – Part 1: Practical Code Separation

LinkedInTwitterGoogle+FacebookRedditEmail

At the time of writing, I’m pretty new to using Xamarin in a professional context. I’ve been fiddling with it on and off for a few years now, and have had the opportunity to use it for a few projects this year. I’ve learned a few rather important things, that I’d like to share in a series of posts, as they are related to your project’s square zero – architecture.

It is important to realize that one of the largest differences between Xamarin based architecture and “normal” mobile project architecture (Xcode, etc), is that we’re no longer operating in the world of Model-View-Controller (MVC). Rather, we are in the brave new world of Model-View-ViewModel (MVVM). This change means we’ll need to rethink most of what we already know about architecting mobile applications. Trust me when I say it’s far better to adjust early on, than try to shoe Xamarin into the MVC mindset.

When I was first researching Xamarin, the graphics on this page (and its previous iterations) made a profound impact on me. As I had been developing native mobile software professionally for some years, I quickly saw the benefits of a shared “core”. Think about how many times a service will change on you. Think about how many times a model is altered. Think about how many times the business logic is changed, due to feature requests, or fundamental misunderstandings. Staying agile and being able to adapt to these changes can make or break projects. When you are supporting just one platform, say, iOS, it is reasonably manageable. But once you throw another one into the works, and then another, it quickly becomes a nightmare. All of your work is duplicated. All of your bug fixes need to be verified multiple times. Having one platform functioning fine is not sufficiently indicative of whether or not all platforms are bug free. A relief from these worries is elegantly portrayed on the aforementioned page.

As I played with toy projects, and progressed through Xamarin University, I would architect my projects like so:

 

  • Solution: ProjectName
    • Project: ProjectName.iOS
    • Project: ProjectName.Android
    • Project: ProjectName.Shared

 

As these were small scale exercises, it wasn’t a big deal. Then, when Xamarin.Forms was announced, I took to essentially replacing the Shared project with the Forms project, as illustrated:

 

  • Solution ProjectName
    • Project: ProjectName.iOS
    • Project: ProjectName.Android
    • Project: ProjectName.Forms

 

In both situations, Shared or Forms would house ALL of the reusable code. Strictly speaking, this was a complete upgrade from managing an Objective-C and a Java codebase simultaneously. However, there are some problems here, that may not be immediately apparent.

To understand our current shortcomings, it is important to examine one of Xamarin’s biggest strengths. In my opinion, it is NOT the fact that it is cross platform, rather, it is the fact that you’re writing C# code. That may paint me to be some C# fanboy, but I can assure you that you could not be further from the truth. Rather, we should think about what else can be created using C#:

 

  • Windows Phone applications (Universal App)
  • Windows desktop application (Universal App)
  • Windows desktop applications (WPF)
  • Mac desktop application (Xamarin.Mac)
  • Etc

 

Now, what do all of these apps have in common with the iOS and Android apps we’ve written? Well, they all have models, persistence, networking, business logic, test suites, and tons of other stuff.

Can you see the problem now? What if someone asked you to go ahead and slap a WPF app on top of our nice “cross platform” codebase. Well.. that’s tricky. Because now, you are probably using Xamarin.Forms, which is a phenomenal tool, but it is probably all interconnected with your other stuff in the Shared / Forms project.

So, how do we maximize our code reuse, with consideration to either known other platforms, or possible future platforms? Well, we need to extract the items that are so sharable that they have nothing even to do with Xamarin.Forms. I’m talking about your ViewModels, your Models, your networking, and so on. We can simply break things up a bit:

 

Ideal Architecture

 

What we end up with here is an architecture that looks like the following, if you were to walk the levels from client applications down to a shared codebase:

 

At the cost of a bit more organizational overhead, we are now ready to take on essentially any platform in the future, that uses a C# codebase. Now, some of these may not appear, for example, the Net Solution. I’ve recently been using the Azure Mobile Services platform for my networking requirements, and as such, there has been no need to manually interact with HttpClient et al. And of course, the various client platforms you’re targeting will differ.

I’d strongly recommend that even if you’re targeting just one or two platforms, you consider using a similar approach from the beginning, when it is easiest. Not only does it allow you to quickly adapt to new requirements, but it also allows you to leverage the “wow” factor that Xamarin brings. Imagine if you have a spare couple of days and drop a full WPF app on top of your shared iOS and Android core? That will rock people’s worlds, I can attest to that.

 

We’ll revisit some of these architectural decisions in future posts, when we discuss some more in depth concepts, such as where to put different things, and in what way your dependencies should flow, but for now, I’d just like to thank all of you who’ve walked through this with me, and welcome all comments below. I think this is an great area of discussion that pushes the already incredible Xamarin to exciting new levels.

LinkedInTwitterGoogle+FacebookRedditEmail

Xamarin Certification – Complete!

LinkedInTwitterGoogle+FacebookRedditEmail

I love Xamarin. There, I said it! It is an incredibly bright beacon in the mobile landscape, and one that I believe will lead our industry to new and exciting avenues.

So, what is it? Xamarin is mobile application development platform, specializing in that same pitch you’ve heard one hundred times before, the golden, radiant, trumpet blare inducing, cross-platform codebase enabler. Except this time, they hype is real.

A few years back I stumbled across this curious piece of tooling, way back before Xamarin Studio was a thing. I’d already been wholly unimpressed by the PhoneGaps and Titaniums of the day, and was not expecting very much. What I found though, while not even remotely ready for primetime, was the start of something incredible.

What Xamarin manages to get right, what everyone else manages to get so wrong, is that their final product doesn’t just look like a native application, doesn’t just feel like a native application, but indeed, it IS a native application. And that’s a pretty huge deal.

Now, back in the day Xamarin was not a pleasant thing to work with, to be completely honest. You had the option of doing file linking, or using conditional compilation, to share your code. While the premise was great, the execution was lacking. But then, something incredible came into play, and that something was the humble PCL.

A PCL is a Portable Class Library, and while I won’t bore you with the details (yet!), know that it allowed you to write C# code that was capable of targeting multiple different platforms, by leveraging their feature intersections, via Profiles. Now, we were able to have a real library project in our Solution, and not have to litter the file with #ifdef and hurt our caveman brains juggling file linking. It was about this time that I began focusing every moment of my rare free time on learning Xamarin. I could tell it was a boat I didn’t want to miss.

Eventually the last piece of the puzzle came into play, Xamarin.Forms. This phenomenal toolkit allows you to write most of your UI code, once. No more having to mess with Storyboards and AXML files, just one and done. Plus you get all of the wonders that XAML brings to the table. Data Binding, Commands, oh my! It functions essentially like a UI PCL, targeting the intersections of the various platform UI components.

For example, a Forms ListView captures the idea of an iOS UITableView, an Android ListView, and so on. It is a convenient distillation that allows you to rapidly produce high quality user interfaces.

Then, in Spring 2014 I decided to enroll in the newly minted Xamarin University. I learned quite a bit of stuff there, the most valuable of which being the Forms related items, as they were hot off the press while I was enrolled. The instructors were always very friendly, and quick to answer every single question posed.

My journey concluded this past month, when I finally got around to completing their rather large competency exam. It was pretty brutal, 150 questions take over a few hour period, but I survived, and was rewarded with this shiny badge:

 

Xamarin Certified Mobile Developer Badge-medium res

 

Isn’t it lovely? I’m quite proud of it!

Now, I was just kidding when I said my journey was over, it is very much just beginning. I’ve been lucky enough to work on a few Xamarin projects this past month with some extremely senior C# developers, and have come to realize I’m only just scratching the surface of what C#, MVVM, Xamarin, and all the other goodies have to offer.

I will be using this blog to chronicle all of the stuff I learn and encounter. Whether it’s a great library, a solid architectural approach, or a sneaky pitfall, I’ll be reporting back here. That said, I pride myself on being platform agnostic, so there will surely be tons of other stuff popping up here and there.

LinkedInTwitterGoogle+FacebookRedditEmail