Xamarin.Froms: Dependency Injection

comments edit

To recap, I’m writing a shopping cart app for Windows Phone, Android, and iOS. The purpose of the app is primarily to let me use Forms. Each post will build on top of the previous one.

Last time I added a product search that uses a barcode scanner using the ZXing component. Today I plan on cleaning up app startup by incorporating a dependency injection framework.

Recap and Code

This is the sixth post in the series, you can find the rest here:

  • Day 0: Getting Started (blog / code)
  • Day 1: Binding and Navigation (blog / code)
  • Day 2: Frames, Event Handlers, and Binding Bugs (blog / code)
  • Day 3: Images in Lists (blog / code)
  • Day 4: Search and Barcode Scanner (blog / code)
  • Day 5: Dependency Injection (blog / code)
  • Day 6: Styling (blog / code)
  • Day 7: Attached Behaviors (blog / code)
  • Day 8: Writing to Disk (blog / code)
  • Day 9: App and Action Bars (blog / code)
  • Day 10: Native Views (blog / code)

For a full index of posts, including future posts, go to the GitHub project page.

Cleanup

Before starting up, I’d like to perform a little bit of clean up. There is a bug in the XF template. When the reference for the platform project (e.g., ShoppingCart.WinPhone) to the core project (i.e., ShoppingCart) is created the project id is missing.

This causes a few subtle problems, the most annoying of which is that renames in the core project are not propagated to the dependent projects. For instance, if I rename the FirstPage property of the App class, the reference in ShoppingCart.WinPhone.MainPage will not be updated.

This can easily be solved by

  1. Removing the reference to ShoppingCart from each of the platform projects
  2. Adding the reference back

As a reminder, to remove the reference, just expand the References node under ShoppingCart.WinPhone in Solution Explorer, select the reference, and hit the delete key.

To add the reference back, right click on the References node, select Add Reference, and tick the checkbox next to ShoppingCart in the Projects tab.

Doing a quick diff of your CSPROJ after this you can see that the Project element has been added to the reference.

<!-- Before -->
<ProjectReference Include="..\ShoppingCart\ShoppingCart.csproj">
    <Name>ShoppingCart</Name>
</ProjectReference>
<!-- After -->
<ProjectReference Include="..\ShoppingCart\ShoppingCart.csproj">
    <Project>{8eb80e50-ef54-451b-9768-3d38e2a3e122}</Project>
    <Name>ShoppingCart</Name>
</ProjectReference>

Dependency Service vs. Injection

Last week I used XF’s DependencyService class to resolve application specific dependencies. This worked by registering the dependency in the Android and WinPhone projects by adding a Dependency attribute like this:

[assembly: Xamarin.Forms.Dependency(typeof(DroidScanner))]

and then resolving it in the core project with a call to DependencyService.Get

var scanner = DependencyService.Get<IScanner>();

While this worked for what I needed last week, it does have the requirement that resolved type (i.e., DroidScanner in my example) has a default constructor. This means that unlike a dependency injection framework, you cannot rely on the framework to create all of your dependencies in one go. You have to manually resolve and compose them yourself.

Dependency Injection on PCL

There are many .Net DI frameworks out there. My go to DI framework is Ninject but as of now it doesn’t support PCL. So, after a little digging for PCL frameworks. The key features that I look for are

  • Constructor injection
  • Registration with generics

I decided to give AutoFac a try. I’ve never used it before, but by looking at the documentation it looked like it meets my requirements.

Starting Up AutoFac

The first thing I need to do is to get AutoFac. In my main project (ShoppingCart) I right click to add a nuget package, search for AutoFac, and cross my fingers that it installs with out complaint. Somewhat to my surprise, NuGet downloaded and added it to my project with out complaint. I know it claimed to be PCL friendly, but I’m always surprised when installing something just works the first time.

Before I remove the usage of DependencyService, I need to configure the rest of the services and view models to be created by the DI framework. I’ll do this in a dedicated class called ContainerCreator. This is a habit I got from Ninject where you can create module classes to do all your bindings. It keeps everything in one place and I like it in Ninject so I’ll see how well it works in AutoFac land.

public class ContainerCreator
{
  public static IContainer CreateContainer()
  {
    ContainerBuilder cb = new ContainerBuilder();
 
    // Services
    cb.RegisterType<LoginService>().As<ILoginService>().SingleInstance();
    cb.RegisterType<ProductLoader>().As<IProductLoader>().SingleInstance();
    cb.RegisterType<ProductService>().As<IProductService>().SingleInstance();
    cb.RegisterType<NavigationService>().As<INavigationService>().SingleInstance();
    cb.RegisterInstance(DependencyService.Get<IScanner>()).As<IScanner>().SingleInstance();
 
    // View Models
    cb.RegisterType<CategoriesListViewModel>().SingleInstance();
    cb.RegisterType<LoginViewModel>().SingleInstance();
    cb.RegisterType<ProductsListViewModel>().SingleInstance();
    cb.RegisterType<ProductViewModel>().SingleInstance();
    cb.RegisterType<WelcomeViewModel>().SingleInstance();
 
    return cb.Build();
  }
}

I’m setting up all of my registrations for my services which implement interfaces and my view models which are registered to themselves. I’m also registering everything as singletons which will probably change later, but this should get me going. Again, I’m still using the DependencyService to get my IScanner, this is just an intermediary step for now. The goal is to remove that by the end of this post.

Next, I’ll clean up App to make use of the AutoFac container

private static readonly IContainer _container;
 
static App()
{
    _container = ContainerCreator.CreateContainer();
 
    NaviService = _container.Resolve<INavigationService>() as NavigationService;
 
    // Pages
    WelcomePage = new WelcomePage();
    LoginPage = new LoginPage();
    CategoriesListPage = new CategoriesListPage();
}

The view model properties now just resolve their values directly from the container when called. They are all pretty much the same, here’s one as an example.

public static CategoriesListViewModel CategoriesListViewModel
{
    get
    {
        return _container.Resolve<CategoriesListViewModel>();
    }
}

Starting the app up, it should work exactly like it did before. And it does. Success.

Removing DependencyService

Now we can get to work on removing the DependencyService. Technically though there is no reason just yet to remove it. It works just fine for my app because DroidScanner and WinPhoneScanner both have parameterless constructors. So I’m going to break it now by adding some parameters. The most common parameter in most of my apps is a logger, so I’ll add one here.

I’ll add ILogger, an interface for my logger:

public interface ILogger
{
    void Info(string message);
    void Info(string format, params object[] args);
    void Info(Exception ex, string message);
    void Info(Exception ex, string format, params object[] args);
 
    void Error(string message);
    void Error(string format, params object[] args);
    void Error(Exception ex, string message);
    void Error(Exception ex, string format, params object[] args);
}

And then a Droid and WinPhone specific implementations each using their platform specific methods for logging: Log and Debug.WriteLine respectively. They are kind of long and boring, so here’s just a simple example from both:

public class DroidLogger : ILogger
{
    private const string APP_NAME = "ShoppingCart";
 
    public void Info(string message)
    {
        Log.Info(APP_NAME, message);
    }
}
public class WinPhoneLogger : ILogger
{
    public void Info(string message)
    {
        Console.WriteLine("INFO:  " + message);
    }
}

Next we add logging to each of the IScanner implementations. Here’s the WinPhone implementation, the Droid version is identical

private readonly ILogger _logger;
 
public WinPhoneScanner(ILogger logger)
{
    _logger = logger;
}
 
public async Task<ScanResult> Scan()
{
    _logger.Info("Starting the barcode scanner.  Stand back.");
 
    var scanner = new MobileBarcodeScanner(MainPage.DispatcherSingleton);
    // ...
}

Hooray, the call to DependencyService.Get now fails with this error: System.MissingMethodException: No parameterless constructor defined for this object. Time to fix it.

First I’m going to change the name of the ContainerCreator to AppSetup and make it a non-static class. My plan is to enable custom app setup by overriding methods in this object. Here’s what it looks like now:

public class AppSetup
{
    public IContainer CreateContainer()
    {
        ContainerBuilder cb = new ContainerBuilder();
        RegisterDepenencies(cb);
        return cb.Build();
    }
 
    protected virtual void RegisterDepenencies(ContainerBuilder cb)
    {
        // Services
        cb.RegisterType<LoginService>().As<ILoginService>().SingleInstance();
        cb.RegisterType<ProductLoader>().As<IProductLoader>().SingleInstance();
        cb.RegisterType<ProductService>().As<IProductService>().SingleInstance();
        cb.RegisterType<NavigationService>().As<INavigationService>().SingleInstance();
 
        // View Models
        cb.RegisterType<CategoriesListViewModel>().SingleInstance();
        cb.RegisterType<LoginViewModel>().SingleInstance();
        cb.RegisterType<ProductsListViewModel>().SingleInstance();
        cb.RegisterType<ProductViewModel>().SingleInstance();
        cb.RegisterType<WelcomeViewModel>().SingleInstance();
    }
}

The registrations have been moved to a dedicated method RegisterDependencies which takes the ContinerBuilder to use to add your registrations. I’ve removed the instance registration that was was using the XF DependencyService (that was the goal the whole time). If you notice, the method is virtual. The idea is to override this for each platform that needs to. Here’s the WinPhone override (the Droid version is very similar):

public class WinPhoneSetup : AppSetup
{
    protected override void RegisterDepenencies(ContainerBuilder cb)
    {
        base.RegisterDepenencies(cb);
 
        cb.RegisterType<WinPhoneLogger>().As<ILogger>().SingleInstance();
        cb.RegisterType<WinPhoneScanner>().As<IScanner>().SingleInstance();
    }
}

All that I’m doing here is registering the WinPhone logger and scanner. The two bits of platform specific implementations that I have. Notice that I call into my base implementation to handle all of the rest of the registrations.

There’s a small problem though. The WinPhoneSetup class won’t compile. It doesn’t know anything about AutoFac. Right now only my core project references AutoFac. I could just add a reference for the WinPhone project, but I know that all of the other projects will need one as well, so I’ll add a reference for each of the projects in one go. The easiest way to do this is to right click on the Solution (not the projects) and select Manage NuGet Packages for Solution. From there you can select the Installed Packages tab and click the “Manage” button for AutoFac. Then just tick all of the check boxes and click OK.

Next in order to have App be able to use different versions of AppSetup I change the static constructor to a static method called Initialize that takes the AppSetup object to use.

public static void Init(AppSetup appSetup)
{
    _container = appSetup.CreateContainer();
 
    NaviService = _container.Resolve<INavigationService>() as NavigationService;
 
    WelcomePage = new WelcomePage();
    LoginPage = new LoginPage();
    CategoriesListPage = new CategoriesListPage();
 
    // Startup Page
    StartupPage = WelcomePage;// CategoriesListPage;
}

Now all I need to do is to call Init from the Droid and WinPhone projects. In MainActivity.OnCreate we add the call Init with the DroidSetup object

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    Xamarin.Forms.Forms.Init(this, bundle);
    App.Init(new DroidSetup());
    SetPage(App.StartupPage);
}

And in the constructor for MainPage.xaml.cs we call Init with an instance of WinPhoneSetup.

public MainPage()
{
    InitializeComponent();
    Forms.Init();
 
    App.Init(new WinPhoneSetup());
    Content = ShoppingCart.App.StartupPage.ConvertPageToUIElement(this);
}

With AutoFac in place I can delete the two ServiceRegistration classes I had that registered my classes with the DependencyService. And now all I have to do is to spin up the app and see that the log messages in the console.

Happy Coding

this post was originally on the MasterDevs Blog

Comments