Category Archives: Uncategorized

Caliburn Micro Part 7: Basic Dependency Injection With WinRT and Phone 8.1

This tutorial is mostly targeted at Windows Phone development but most of it will carry over to Windows 8 store apps and to a certain extent, desktop apps.

Caliburn makes available the WinRTContainer which can be used to register dependencies. The different ways they can be registered are listed below.

RegisterInstance – The registered instance will be returned each request
RegisterPerRequest – A new instance of the specified type will be returned each time
RegisterSingleton – Similar to register instance but singletons are only constructed when the first request is made
Handler – Provides a way of adding logic for context sensitive implementations
AllTypesOf – Registers all specified types in an assembly as singletons

Example

Say we had a small application that allowed the adding of users. The viewmodel takes a single parameter in its constructor which is an interface to a database.

public class AddUsersViewModel
{
    public AddUsersViewModel( IDataStore dataStore )
    {
    }
}

In this instance we only want one instance of the AddUsersViewModel to exist at a time so we register it as a singleton with the container. The code below is from App.xaml.cs.

protected override void Configure()
{
    container = new WinRTContainer();

    container.RegisterWinRTServices();

    container.RegisterSingleton( typeof( AddUsersViewModel ), null, typeof( AddUsersViewModel ) );
}

Now given that our viewmodel takes arguments in its constructor, we want Caliburn to inject those for us when it creates the singleton instance of it. Note that _dataStore is an instance of IDataStore that we have created.

protected override void Configure()
{
    container = new WinRTContainer();

    container.RegisterWinRTServices();

    container.RegisterInstance( typeof( IDataStore ), null, _dataStore );

    container.RegisterSingleton( typeof( AddUsersViewModel ), null, typeof( AddUsersViewModel ) );
}

With the above code caliburn will automatically inject our instance of IDataStore into the constructor of AddUsersViewModel when it creates an instance of it. This is especially useful when you are using the navigation service in Windows Phone 8.1 apps.