Accessing platform specific code using IOC in MVVM Cross

Accessing platform specific code using IOC in MVVM Cross

Sometimes we need to write code specific to platform which cannot be written in View Model and needs to be accessed by the View Model. For example, you want to display a message using MessageDialog but its not possible to write the code in the View Model. In this case we can create an interface in the View Model and implement the platform specific code in the Windows 10 project.

Lets see how to do this in detail.

Step 1 : Creating Interface in the View Model

Create an IPageHelper interface in the View Model with ShowMessage method.


    public interface IPageHelper
    {
       void ShowMessage(string message);
    }

Step 2 : Implement the Platform Specific Code.

Create an PageHelper class implementing the MessageDialog class to display the message to the user.

    public class PageHelper : IPageHelper
    {
        public const string AppName = "Daily Dot net Tips";

        public async void ShowMessage(string message)
        {
            try
            {
                MessageDialog msg = new MessageDialog(message, AppName);
                msg.Commands.Add(new UICommand("Ok"));
                await msg.ShowAsync();
            }
            catch
            {
            }
        }
    }

Step 3 : override the InitializeFirstChance method

Go to the SetUp.cs file and override the InitializeFirstChance method.
Register the class and interface as Singleton as shown below.

protected override void InitializeFirstChance()
{
Mvx.RegisterSingleton<IPageHelper>(new PageHelper());
base.InitializeFirstChance();
}

Step 4: Invoke the Method.

That’s it. Now your class is registered as singleton and whenever required we can invoke it by resolving the interface.

var pagehelper = Mvx.Resolve<IPageHelper>();
pagehelper.ShowMessage(MessageConstants.NoRecordsFoundMessage);

Now you can run the app. The message dialog gets displayed.

IOCMVVM

Hope this post might have helped.

Arun Kumar

Arun kumar Surya Prakash, is a  Developer  Consultant. He  is a Microsoft Certified Solution  Developer  for Store App Development, and a Azure Solution Developer. His core skills is on developing Windows Store App and Cross Platform App development. You can follow him @arunnov04

One Comment to “Accessing platform specific code using IOC in MVVM Cross”

Comments are closed.