Reza
Reza

Reputation: 5634

Dependency injection and base classes

This is in a xamarin.forms app using Prism, but the question is more a foundational c# question that I am confusing myself over.

I am using dependency injection and my types are registered in the app.xaml.cs file -> RegisterTypes method.

    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.RegisterDialog<BusyDialog, BusyDialogViewModel>();

        containerRegistry.RegisterForNavigation<NavigationPage>();
        containerRegistry.RegisterForNavigation<MainPage, MainPageViewModel>();
    }

My base view model ctor is defined as:

    public ViewModelBase(INavigationService navigationService, IDialogService dialogService)
    {
        NavigationService = navigationService;
        DialogService = dialogService;
    }

And all the other viewmodels derive this base class. Eg.

    public MainPageViewModel(INavigationService navigationService, IDialogService dialogService)
        : base(navigationService, dialogService)
    {
    }

My question is that, in this MainPage ctor, I am injecting 'INavigationService navigationService, IDialogService dialogService'. Across all my viewmodels I am using NavigationService and DialogService (from the base class) so isn't this redundant code?

I have about 20 viewmodels, I added the IDialogService to my baseclass and realized that I have to update the constructors in every viewmodel.

Is there a way to just inject into the baseclass and usable by all classes that derive this baseclass without having to specify in the class constructors?

Upvotes: 2

Views: 1476

Answers (1)

Jeremy Lakeman
Jeremy Lakeman

Reputation: 11090

The simple way to inject dependencies into a base type is to define a new type to hold onto all the dependencies;

public class ViewModelBaseDependencies{
    public ViewModelBaseDependencies(INavigationService navigationService, IDialogService dialogService){
    //...
}
public ViewModelBase(ViewModelBaseDependencies dependencies)
{
    NavigationService = dependencies.NavigationService;
    DialogService = dependencies.DialogService;
}
public MainPageViewModel(ViewModelBaseDependencies dependencies)
        : base(dependencies)

Then you only need to pass the one constructor argument and can trivially add new dependencies.

Upvotes: 2

Related Questions