Windows 8 App using Unity 3 IoC

Unity.3.0.1304.1 now supports Windows 8 Apps with the Microsoft.Practices.Unity.NetCore assembly. This is a reduced set of features compared with the full version of Unity. This blog demonstates how this IoC container could be used with a default Windows 8 App.

Step 1: Get Unity using nuget:
NugetUnityWin8

Step 2: Create a UnityHelper class which will be used to register the interfaces, classes:

using System;
using Microsoft.Practices.Unity;

namespace UnityTestWin8App
{
    public class UnityHelper
    {
        #region Unity Container
        private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
        {
            var container = new UnityContainer();
            RegisterTypes(container);
            return container;
        });

        /// <summary>
        /// Gets the configured Unity container.
        /// </summary>
        public static IUnityContainer GetConfiguredContainer()
        {
            return container.Value;
        }
        #endregion

        public static void RegisterTypes(IUnityContainer container)
        {
            // Your registration logic ...
            container.RegisterTypes(AllClasses.FromApplication(false,false),
                                    WithMappings.FromMatchingInterface,
                                    WithName.Default,
                                    WithLifetime.ContainerControlled
                                );
        }
    }
}

Step 3: Now create a locator class which will be used in all the views. This class will return the resolved instance registered in the UnityHelper.

using Microsoft.Practices.Unity;

namespace UnityTestWin8App
{

    public class Locator : IServiceLocator
    {
        private readonly IUnityContainer _container = UnityHelper.GetConfiguredContainer();

        public T Resolve<T>()
        {
            return _container.Resolve<T>();
        }
    }

    public interface IServiceLocator
    {
        T Resolve<T>();
    }
}

Step 4: A class instance can then be used in a Windows 8 App Page

public sealed partial class GroupedItemsPage : UnityTestWin8App.Common.LayoutAwarePage
    {
        private IData1Repository _data1Repository;

        public GroupedItemsPage()
        {
            IServiceLocator serviceLocator = new Locator();
            _data1Repository = serviceLocator.Resolve<IData1Repository>();

            this.InitializeComponent();
            
        }

And it can be used as follows:

 void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            _data1Repository.GetData1();
            _data1Repository.GetData2();
            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            var itemId = ((SampleDataItem)e.ClickedItem).UniqueId;
            this.Frame.Navigate(typeof(ItemDetailPage), itemId);
        }

So what’s the advantage of this? We still have a direct coupling to the Locator class in the constructor of the views.

The main advantage is that the DataAccessLayer assembly uses only constructor injection and this can be tested or changed in the future as required. The IData1Repository is also resolved in the constructor so we could change the implementation if required by changing only the registration in the UnityHelper class and no where else.

namespace DataAccessLayer
{
    public class Data1Repository : IData1Repository
    {
        private readonly IFile1Repository _file1Repository;

        public Data1Repository(IFile1Repository file1Repository)
        {
            _file1Repository = file1Repository;
        }

        public string GetData1()
        {
            return _file1Repository.GetFileNameTest();
        }

        public string GetData2()
        {
            return "GetData2";
        }
    }
}

Code: https://github.com/damienbod/UnityWithWin8App

Limitations of Unity NetCore (Taken from msdn)

The UnityServiceLocator Class

You cannot use the Microsoft.Practices.Unity.UnityServiceLocator class with the .NET for Windows Store apps version of the .NET Framework. This class depends on the Common Service Locator library, which is not available for Windows Store apps.

Unity Design-time Configuration

You cannot configure your Unity container using a configuration file such as app.config. Windows Store apps must configure Unity containers programmatically.

This is because the Unity.Configuration assembly is not compatible with Windows Store apps.

Unity Interception

Unity Interception is not available to Windows Store apps.

This is because the Unity.Interception and Unity.Interception.Configuration assemblies are not compatible with Windows Store apps.

Links:
http://unity.codeplex.com/

http://unity.codeplex.com/discussions/455740

3 comments

  1. This is good news. I’ve started playing with Windows 8 apps and I’ve been looking for an IoC container that works with that platform too.

  2. Excume! I ‘m from Bolivia!

    I have problem

    “AllClasses.FromApplication(false,false)” not is visible

    container.RegisterTypes(AllClasses.FromApplication(false,false),
    WithMappings.FromMatchingInterface,
    WithName.Default,
    WithLifetime.ContainerControlled
    );

  3. Hi Luis
    AllClasses is in the Microsoft.Practices.Unity assembly. Do you have a reference to this? (Unity 3.0.1304.1 NuGet Package)

    Greetings Damien

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: