Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a Unity IoC container with Template10?

I have an app based on Template10 and want to handle my dependency injection using IoC. I am leaning toward using Unity for this. My app is divided into three assemblies:

  1. UI (Universal app)
  2. UI Logic (Universal Library)
  3. Core Logic (Portable Library).

I have these questions:

  1. Should I use a single container for the whole app, or create one for each assembly?
  2. Where should I create the container(s) and register my services?
  3. How should different classes in the various assemblies access the container(s)? Singleton pattern?

I have read a lot about DI and IoC but I need to know how to apply all the theory in practice, specifically in Template10.

The code to register:

// where should I put this code?
var container = new UnityContainer();
container.RegisterType<ISettingsService, RoamingSettingsService);

And then the code to retrieve the instances:

var container = ???
var settings = container.Resolve<ISettingsService>();
like image 300
Christoffer Reijer Avatar asked May 26 '16 05:05

Christoffer Reijer


1 Answers

I not familiar with Unity Container.

My example is using LightInject, you can apply similar concept using Unity. To enable DI on ViewModel you need to override ResolveForPage on App.xaml.cs on your project.

public class MainPageViewModel : ViewModelBase
{
    ISettingsService _setting;
    public MainPageViewModel(ISettingsService setting)
    {
       _setting = setting;
    }
 }


[Bindable]
sealed partial class App : Template10.Common.BootStrapper
{
    internal static ServiceContainer Container;

    public App()
    {
        InitializeComponent();
    }

    public override async Task OnInitializeAsync(IActivatedEventArgs args)
    {
        if(Container == null)
            Container = new ServiceContainer();

        Container.Register<INavigable, MainPageViewModel>(typeof(MainPage).FullName);
        Container.Register<ISettingsService, RoamingSettingsService>();

        // other initialization code here

        await Task.CompletedTask;
    }

    public override INavigable ResolveForPage(Page page, NavigationService navigationService)
    {
        return Container.GetInstance<INavigable>(page.GetType().FullName);
    }
}

Template10 will automaticaly set DataContext to MainPageViewModel, if you want to use {x:bind} on MainPage.xaml.cs :

public class MainPage : Page
{
    MainPageViewModel _viewModel;

    public MainPageViewModel ViewModel
    {
      get { return _viewModel??(_viewModel = (MainPageViewModel)this.DataContext); }
    }
}
like image 97
Ask Too Much Avatar answered Nov 07 '22 09:11

Ask Too Much