Dependency Injection using Template 10

会有一股神秘感。 提交于 2019-12-01 12:39:04
Juan

I made it work (but In my case I'm having another anoying issue I'll mention later and probably in a SO quiestion too).

On the one hand, the Ask Too Much's answer to this question guided me to solve this problem with ViewModel's DI.

In App.xaml.cs:

public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
{
    // long-running startup tasks go here
    AppController.Initialize();
    await Task.CompletedTask;
}

AppController is the place where I configure the app, including the container.

next, in App.xaml.cs:

public override INavigable ResolveForPage(Page page, NavigationService navigationService)
{
    if (page is MainPage)
    {
        return SimpleIoc.Default.GetInstance<MainPageViewModel>();
        //(AppController.UnityContainer as UnityContainer).Resolve<INavigable>();
    }
    else
        return base.ResolveForPage(page, navigationService);
}

But you also have to:

Remove <Page.DataContext> from the Page XAML. Remove constructors from page.xaml.cs, my MainPage.xaml.cs is like this

public sealed partial class MainPage : Page
{
    MainPageViewModel _viewModel;

    public MainPageViewModel ViewModel
    {
        get { return _viewModel ?? (_viewModel = (MainPageViewModel)DataContext); }
    }    
}

Inject your dependencies on your VM:

public MainPageViewModel(IShapeService shapeService)
{     
   // this is just a POC            
}

And that's all, it should work for you.

I updated the wiki with this same information in a while... Also, just let you know that I made it to work with Unity and with MVVMLight.SimpleIoC with same result, a System.PlatformNotSupportedException due to what IShapeService really is is a WCF proxy that is in a PCL library that I'll have to refactor because I just realize that UWP doesn't support config files (lol!)

I hope it helps and save you time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!