Skip to content
This repository was archived by the owner on Aug 27, 2020. It is now read-only.

XamUInfrastructure

Mark Smith edited this page Sep 2, 2016 · 2 revisions

XamUInfrastructure

The XamUInfrastructure static class provides methods to initialize all the service implementations and the service locator or IoC container.

Properties

Methods

Example

public class App : Application
{
   public App()
   {
      IDependencyService ds = XamUInfrastructure.Init();
      ds.Register<MainViewModel>();
      MainPage = new NavigationPage(new MainPage());
   }
}

Changing the Service Locator

By default, the library uses the static DependencyService built into Xamarin.Forms. However, you can change this by supplying a different implementation of the IDependencyService abstraction to the XamUInfrastructure.Init() method. For example, you could wrap the Unity Container.

First, turn it into a IDependencyService:

public class UnityWrapper : IDependencyService
{
    UnityContainer container;

    public UnityWrapper(UnityContainer container)
    {
       this.container = container;
    }

    public T Get<T>() where T : class
    {
        return container.Resolve<T>();
    }

    public void Register<T> () where T : class, new()
    {
        container.RegisterType<T>();
    }

    public void Register<T, TImpl> () 
        where T : class
        where TImpl : class, T, new()
    {
        container.RegisterType<T,TImpl>();
    }
}

Then, pass your implementation into the Init method:

// Setup Unity
var container = new UnityWrapper(new UnityContainer());

// Initialize our services - pass in the container we want to use
IDependencyService ds = XamarinUniversity.Services.XamUInfrastructure.Init(container);
ds.Register<MainViewModel>();
ds.Register<ISomeOtherService, SomeImplementation>();
...