You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Xamarin MVVMLight(SimpleIoc)代码迁移至Xamarin Prism(DryIoc)?

Migrating MVVMLight SimpleIoc ViewModelLocator Setup to Prism with DryIoc in Xamarin

Got it, let's walk through how to smoothly migrate your ViewModelLocator configuration from MVVMLight's SimpleIoc to Prism with DryIoc in your Xamarin app. I'll break this down into clear, actionable steps based on common MVVMLight patterns you're probably using.

First, Understand the Core Difference

In MVVMLight, you typically set up dependencies and ViewModel mappings via the ViewModelLocator class (either via code registration or conventions). With Prism + DryIoc, all container configuration lives in your App.xaml.cs (which inherits from PrismApplication), specifically in the RegisterTypes method. Prism also handles View-ViewModel DataContext binding automatically, so you won't need most of the ViewModelLocator boilerplate.

Step 1: Migrate Service Registrations

Any services you registered in SimpleIoc will move directly to the RegisterTypes method using DryIoc's registration syntax.

MVVMLight (Old Code)

// In your ViewModelLocator or app startup
SimpleIoc.Default.Register<IMyApiService, MyApiService>();
SimpleIoc.Default.Register<ILocalStorageService, LocalStorageService>(true); // Singleton

Prism + DryIoc (New Code)

In your App.xaml.cs's RegisterTypes method:

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    // Register transient service (new instance every time it's resolved)
    containerRegistry.Register<IMyApiService, MyApiService>();
    
    // Register singleton service (single instance across the app)
    containerRegistry.Register<ILocalStorageService, LocalStorageService>(Reuse.Singleton);
}

Step 2: Migrate View-ViewModel Mappings

MVVMLight's ViewModelLocator uses conventions or manual registration to link Views to ViewModels. Prism supports both convention-based mapping and explicit registration.

Option 1: Convention-Based Mapping (No Manual Registration)

Prism's default convention works just like MVVMLight's:

  • Place Views in a Views folder, ViewModels in a ViewModels folder
  • Name your ViewModel as [ViewName]ViewModel (e.g., MainPage → MainViewModel)

If you follow this structure, Prism will automatically resolve and bind the ViewModel to the View's DataContext without any extra code. Perfect for keeping things clean!

Option 2: Explicit Registration (For Non-Standard Naming/Folders)

If your View/ViewModel pairs don't follow the convention, use RegisterForNavigation to explicitly map them—this replaces MVVMLight's manual ViewModelLocator.Register calls.

MVVMLight (Old Code)

ViewModelLocator.Register(typeof(HomeView).ToString(), () => 
    new HomeViewModel(SimpleIoc.Default.GetInstance<IMyApiService>()));

Prism + DryIoc (New Code)

In RegisterTypes:

// Explicitly map HomeView to HomeViewModel
containerRegistry.RegisterForNavigation<HomeView, HomeViewModel>();

// If you need to register the ViewModel independently (e.g., for constructor injection elsewhere)
containerRegistry.Register<HomeViewModel>(Reuse.Transient);

Step 3: Custom ViewModel Creation Logic (If Needed)

If you used ViewModelLocator.SetDefaultViewModelFactory to customize how ViewModels are created (e.g., adding logging, custom initialization), Prism lets you replace the default IViewModelFactory with your own implementation.

MVVMLight (Old Code)

ViewModelLocator.SetDefaultViewModelFactory((viewType, viewModelType) =>
{
    var viewModel = SimpleIoc.Default.GetInstance(viewModelType);
    // Custom logic here (e.g., set a common property)
    if (viewModel is BaseViewModel baseVm)
        baseVm.NavigationService = SimpleIoc.Default.GetInstance<INavigationService>();
    return viewModel;
});

Prism + DryIoc (New Code)

  1. Create a custom IViewModelFactory:
public class CustomViewModelFactory : IViewModelFactory
{
    private readonly IContainer _container;

    public CustomViewModelFactory(IContainer container)
    {
        _container = container;
    }

    public object CreateViewModel(Type viewModelType)
    {
        var viewModel = _container.Resolve(viewModelType);
        
        // Add your custom initialization logic here
        if (viewModel is BaseViewModel baseVm)
            baseVm.NavigationService = _container.Resolve<INavigationService>();
        
        return viewModel;
    }
}
  1. Register it in RegisterTypes:
containerRegistry.Register<IViewModelFactory, CustomViewModelFactory>(Reuse.Singleton);

Full Example App.xaml.cs

Here's how your final App.xaml.cs might look with all the pieces together:

using Prism.DryIoc;
using Prism.Ioc;
using YourApp.Views;
using YourApp.ViewModels;
using YourApp.Services;

namespace YourApp
{
    public partial class App : PrismApplication
    {
        protected override async void OnInitialized()
        {
            InitializeComponent();
            // Initialize your app's navigation (replace with your root page)
            await NavigationService.NavigateAsync("NavigationPage/MainPage");
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            // Register services
            containerRegistry.Register<IMyApiService, MyApiService>();
            containerRegistry.Register<ILocalStorageService, LocalStorageService>(Reuse.Singleton);

            // Register View-ViewModel pairs
            containerRegistry.RegisterForNavigation<MainPage, MainViewModel>();
            containerRegistry.RegisterForNavigation<DetailPage, DetailViewModel>();

            // Optional: Register custom ViewModel factory
            // containerRegistry.Register<IViewModelFactory, CustomViewModelFactory>(Reuse.Singleton);
        }
    }
}

Key Takeaways

  • All container setup moves to App.xaml.cs's RegisterTypes method—no more ViewModelLocator code in separate files.
  • Prism handles DataContext binding automatically, so you can remove any manual ViewModelLocator.SetAutoWireViewModel calls from your Views.
  • DryIoc's registration syntax is intuitive and aligns with SimpleIoc, so the migration should feel familiar once you get the hang of it.

内容的提问来源于stack exchange,提问作者Chrisgate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:44:27