MvvmCross and IoC

MvvmCross has IoC built-in, in this post I will show how to use it. The Mvx class has a few static metods that you can use for configure the IoC container.

RegisterType
Use the register type method to register new types to the IoC container.

//Register a type
Mvx.RegisterType<IMyType,MyType>();
 
//Register a type as a singleton
Mvx.RegisterSingleton<IMySingleton>(new MySingleton());

Resolve
Use the resolve method to create instances from interfaces.

var myInstance = Mvx.Resolve<IMyType>();

But I recommend to use constructor injection so much as possible. This because you can use it to resolve interfaces in a class library without referencing the assembly that contains the IoC container.

public class MyClass
{
     private IMyType _myType;
 
     public MyClass(IMytype myType)
     {
          _myType = myType;
     }
}

I use to register types in the create app method in the Setup class on each client.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *