Igor Kulman

Developing Windows Store apps with Caliburn Micro Part 4: services and dependency injection

· Igor Kulman

In this installment of the series I will show you how user data services. We will finally use the Unity DI container that is part of the project setup.

Data and Services

In next installment we will be showing a list of products, so let’s create a simple Product class first in the Data directory:

[ImplementPropertyChanged]
public class Product : PropertyChangedBase
{
  public int Id { get; set; }
  public string Name { get; set; }
}

PropertyChangedBase is a base class implementing the INotifyPropertyChanged interface and the ImplementPropertyChanged attribute makes sure it’s method is called for all the property changes. (More about Fody here)

All the operations will be handled by a service implementing the IProductService interface:

public interface IProductService
{
  List<Product> GetAll();
  Product Get(int id);
}

You can implement this interface any way you want. To keep things simple I chose an implementation with two hardcoded products:

public class ProductService: IProductService
{
  private readonly List<Product> _products = new List<Product>()
  {
    new Product
    {
      Id = 1,
      Name = "Product 1"
    },
    new Product
    {
      Id = 2,
      Name = "Product 2"
    }
  };
  
  public List<Product> GetAll()
  {
    return _products;
  }

  public Product Get(int id)
  {
    return _products.SingleOrDefault(l => l.Id == id);
  }
}

Registering services

All our services need to be registered with the Unity DI container before being used. The place to do it is the App class (App.xaml.cs file). You can override the Configure method to do it:

protected override void Configure()
{
  container.RegisterType<IProductService, ProductService>(new ContainerControlledLifetimeManager());
}

This registers the ProductService class to the IProductService interface. The new ContainerControlledLifetimeManager() parameter is Unity’s way of setting the registration to be a singleton.

Injecting services into ViewModel

Injecting the ProductService into our MainViewModel is very simple. Just declare a IProductService variable and initialize it from constructor. Unity will take care of the rest:

[ImplementPropertyChanged]
public class MainViewModel: ViewModelBase
{
  public string Title { get; set; }
  private readonly IProductService _productService;

  public MainViewModel(INavigationService navigationService, IProductService productService) : base(navigationService)
  {
    _productService = productService;
    Title = "Caliburn Demo";
  }
}

Next time we will implement a typical master-detail scenario showing products usign the ProductService whe have created. All the code is again available at GitHub.


See also