2016-06-24 41 views
1

我正嘗試從使用Prism/Unity開發的舊Windows 8.1應用程序將一些代碼遷移到使用模板10和Unity的新UWP應用程序。我在Template 10 here的文檔中看到,您可以使用overrideResolveForPage方法。使用模板10依賴注入

在我的舊的Windows 8.1的應用程序,存在棱鏡Resolve方法,我會override這樣的:

protected override object Resolve(Type type) 
{ 
    return Container.Resolve(type); 
} 

的模板10方法的簽名是

public override INavigable ResolveForPage(Page page, NavigationService navigationService) 

所以我不完全確定如何將其轉換。我已經註冊了我的OnInitializeAsync庫在我App.xaml.cs,像這樣:

Container.RegisterType<IPayeesRepository, PayeesRepository>(new ContainerControlledLifetimeManager()); 

ContainerUnityContainer實例。我的問題是,當我嘗試在另一個頁面上注入依賴項時,我得到一個NullReferenceException,因爲_payeesRepositorynull。在我看來,像依賴注入的構造函數沒有被調用,如果我刪除默認的構造函數,那麼我得到一個錯誤。有沒有人得到團結合作與模板10,可能有什麼建議我可能會失蹤?

我也使用Dependency屬性,像這樣嘗試:

[Dependency] 
private IPayeesRepository _payeesRepository { get; set; } 

但是,這並不工作。好像IPayeesRepository只是沒有被實例化,但我並不確定。在我的Windows 8.1應用程序中,它永遠不會被明確實例化,所以我有一種感覺,它與不覆蓋Resolve方法有關。

+0

配音stylee,我目前正在處理相同的問題,我不得不說,有這個ResolveForPage方法的例子缺乏...如果我找到一個解決方案,我會讓你知道。 – Juan

回答

1

我做了它的工作(但在我的情況下,我有另一個討厭的問題,我會在稍後提及,也可能在SO quiestion)。

一方面,the Ask Too Much's answer to this question引導我用ViewModel的DI解決了這個問題。

在App.xaml.cs:

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

AppController的是我配置的應用程序,包括容器的地方。

接下來,在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); 
} 

但你還必須:

從頁面移除XAML <Page.DataContext>。從page.xaml.cs 刪除構造函數,我MainPage.xaml.cs中是這樣

public sealed partial class MainPage : Page 
{ 
    MainPageViewModel _viewModel; 

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

注入在VM上的依賴關係:

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

而這一切,它應該爲你工作。

I updated the wiki在一段時間內具有相同的信息...此外,讓我們知道我使它與Unity一起工作,並使用MVVMLight.SimpleIoC以及相同的結果,由於IShapeService真正是一個位於PCL庫中的WCF代理,System.PlatformNotSupportedException,我必須重構因爲我只是意識到,UWP不支持配置文件(哈哈!)

我希望它可以幫助並節省您的時間。