Search code examples
c#xamarininitializationmvvmcross

MvvmCross 6.0: How to pass parameter to App on initialization?


after the update to MvvmCross 6.1.2 my code is telling me that the App-class has to have a parameterless constructor. The problem is that until now I passed the filepath to the database to the App using it's constructor.

var dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MyDatabase.db");
return new App(dbPath);

There should be a way to do this, yet I haven't found information on it for MvvmCross 6.0. Can anyone help me out here?


Solution

  • Way 1:

    Instead of passing database path into App constructor, you can get this path into Core, using Mvx registration.

    public interface IDBPathService
    {
        string GetDBPath();
    }
    
    
    public class  DBPathService : IDBPathService
    {
    
        public string GetDBPath()
        {
             return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MyDatabase.db");
        }
    }
    

    In App.cs class there would be Initailize method which should be registering this implementation using

    CreatableTypes() 
        .EndingWith("Service")
        .AsInterfaces()
        .RegisterAsLazySingleton();
    

    Now you can get path using

    var dbpath = Mvx.Resolve<IDBPathService>().GetDBPath();
    

    Way 2:

    Another simpler way is taking static property into your App.cs class and assign path directly from Native projects like.

    In App.cs class define a static property:

    public static string DBPath;
    

    In Platform specific projects assign path like:

    App.DBPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MyDatabase.db");