Integrating DI Containers

Components Context can store global level variables, like for example service container references. In the following sample we'll see how to get access to services inside a component.

Create a new Xamarin Forms project using the Hellp World tutorial (called for example RXAppContainer), add a new .NET standard project (for example called RxAppContainer.Services) and add a reference to it from the XF project, finally remove the MainPage.xaml.

Create a simple service with a method that add 2 numbers in the RxAppContainer.Services project:

public interface ICalcService
{
    double Add(double x, double y);
}

public class CalcService : ICalcService
{
    public double Add(double x, double y) => x + y;
}

Than create a component in the XF project like the following:

public class MainPageState : IState
{
    public double X { get; set; }
    public double Y { get; set; }
    public double Result { get; set; }
}

public class MainPage : RxComponent<MainPageState>
{
    public override VisualNode Render()
    {
        return new RxNavigationPage()
        {
            new RxContentPage()
            { 
                new RxStackLayout()
                {
                    NumericEntry(State.X, v => SetState(s => s.X = v)),
                    new RxLabel(" + ")
                        .FontSize(NamedSize.Large)
                        .VCenter(),
                    NumericEntry(State.Y, v => SetState(s => s.Y = v)),
                    new RxButton(" + ")
                        .OnClick(OnAdd),
                    new RxLabel(State.Result.ToString())
                        .FontSize(NamedSize.Large)
                        .VCenter()
                }
                .Spacing(10)
                .VCenter()
                .HCenter()
                .WithHorizontalOrientation()
            }
            .Title("DI Container Sample")
        };
    }

    private void OnAdd()
    {

    }

    private RxEntry NumericEntry(double value, Action<double> onSet)
        => new RxEntry(value.ToString())
            .OnAfterTextChanged(s => onSet(double.Parse(s)))
            .Keyboard(Keyboard.Numeric)
            .VCenter();
}

Solution should look like this:

In this sample I'm going to use the Microsoft Dependency Injection package to collect and provide services to the app. Add the Microsoft.Extensions.DependencyInjection package to the XF project with the following command or thru Visual Studio tool window:

Install-Package Microsoft.Extensions.DependencyInjection

We now need to register our CalcService with it in the App.xaml.cs:

public App()
{
    InitializeComponent();

    var serviceCollection = new ServiceCollection();
    serviceCollection.AddTransient<ICalcService, CalcService>();

    _app = RxApplication.Create<MainPage>(this)
        .WithContext("ServiceProvider", serviceCollection.BuildServiceProvider())
        .WithHotReload();
}

WithContext() extension method allows us to set application root component context.

Now let's run the app and modify the component OnAdd() method so that it uses the ICalcService

var serviceProvider = (IServiceProvider)Context["ServiceProvider"];
var calcService = serviceProvider.GetService<ICalcService>();
SetState(s => s.Result = calcService.Add(State.X, State.Y));

NOTE: Services must be located in a different project if you want them working with hot reload.

Last updated