Search code examples
c#mvvmcross

Passing parameters to the constructor of a class through MvvmCross's IoC


I have an MvvmCross project in which I have defined a Database class (implementing a IDatabase "service"). This class needs a parameter (the connection string) in the constructor.

Of course, the parameter is known at the level of the application project (WPF, in my case), and not at the level of the library implementing the Database class.

My problem is: how do I pass the parameter when the Database object is created via the IoC container?

I think I should do something similar to

Mvx.RegisterType<IDatabase>(() => new Database("my connection string"));

but I can't find out the right place to write this call. The App class in the top-level WPF project is in no way related to the App class of the "Core" project, so I can't leverage abstract inheritance either.


Solution

  • I finally found it out. The line I wrote in the question was in fact right:

    Mvx.RegisterType<IDatabase>(() => new Database("my connection string"));
    

    What I was missing was where to put that line. The correct place is in a MySetup class, at the application level, that extends MvxWpfSetup<MyApp> - precisely, in the InitializeLastChance() method, that gets called after the Initialize() method of your App class (MyApp, as I called it before).