1

We are trying to implement IoC from xamarin.android in a MvvmCross project. Cannot figure out how to get type specified in IoC container into Setup.cs, of the android project (not ViewModel)

Setup.cs

protected override IMvxIoCProvider CreateIocProvider()
    {
        _provider = base.CreateIocProvider();
        return _provider;
    }
    protected override void InitializeFirstChance()
    {
         _provider.RegisterSingleton<INotificationService>(new NotificationService(ApplicationContext));
        _provider.RegisterType<ITaskFilter>(() => new FilterView());
        base.InitializeFirstChance();
    }

In the Android MvxActivity, we have two possible ways but the first one isn't working and the second one breaks SOLID principles we trying to follow.

 [MvvmCross.Platform.IoC.MvxInject]
 public ITaskFilter TaskFilter { get; set; }

And

 public TasksView()
    {
       var taskFilter = MvvmCross.Platform.IoC.MvxSimpleIoCContainer.Instance.Resolve<ITaskFilter>();
    }

 TaskFilter.Initialize(this); 

I know there is likely to be more required for this question to be answered, please ask for that which you need. Thanks

cfl
  • 999
  • 1
  • 14
  • 34

2 Answers2

3

You don´t need this line to resolve stuff:

MvvmCross.Platform.IoC.MvxSimpleIoCContainer.Instance.Resolve<ITaskFilter>();

It´s as simple as Mvx.Resolve<T> But it´s true that Service Locator pattern is not the best practice.

Mvx normally works with constructor injection, but I´m afraid you can´t use it on android views. Instead, you can do it in the ViewModel:

public ITaskFilter TaskFilter { get; private set };

public YourViewModel(ITaskFilter taskFilter)
{
    this.TaskFilter = taskFilter;
}

Then from your view you can access to ViewModel.TaskFilter

xleon
  • 6,201
  • 3
  • 36
  • 52
  • Thanks @xleon . The interface ITaskFilter is in the android view, because its specific to android and IoC we want there. So would like to keep it out of ViewModel, otherwise dependency is created on the android view interface, from the ViewModel. But as you mentioned there is no way to use it on the android views, so seems like the way we want to do it won't work as hoped. – cfl Jun 27 '16 at 05:47
1

I got this working, with:

public ITaskFilter TaskFilter { get; set; } 
protected override void OnCreate(Bundle bundle)
{
    TaskFilter = Mvx.Resolve<ITaskFilter>();
    TaskFilter.Initialize(this);  
}

Just needed to use Mvx.Resolve No need to use the ViewModel. Just set the IoC container in the setup.cs of Android view then called it.

cfl
  • 999
  • 1
  • 14
  • 34