vendredi 21 février 2020

Differences and similarities between: ViewModelLocator, ServiceLocator, Dependency Injection

I'm confused about the patterns: ViewModelLocator, ServiceLocator, Dependency Injection.

The latest conclusion are as follows:

ViewModelLocator. The place to connect View and ViewModel.

public ViewModelLocator()
{
    SimpleIoc.Default.Register<MainViewModel>();
    SimpleIoc.Default.Register<SettingViewModel>();
}

public MainViewModel MainViewModel => SimpleIoc.Default.GetInstance<MainViewModel>();
public SettingViewModel SettingViewModel => SimpleIoc.Default.GetInstance<SettingViewModel>();

// View
private MainViewModel ViewModel => ViewModelLocator.Current.MainViewModel;

Dependency Injection. A set of principles for weak connections. Often through the constructor.

private readonly INavigationService _navigation;

public ShellViewModel(INavigationService navigation)
{
    _navigation = navigation;
}

ServiceLocator. What is it? The same as ViewModelLocator, but considered by many to be an anti-pattern? It turns out ViewModelLocator is also bad. But how then to connected View and ViewModel? ServiceLocator only needs to store Services? As you understand, all the confusion is from ServiceLocator.

Could you explain the differences and similarities between these elements? To finally uniquely identify and use them correctly. Thank you for any help.

Aucun commentaire:

Enregistrer un commentaire