Search code examples
dependency-injectionmauimaui-shell

In MAUI app, how do I Use Dependency Injection in AppShell


I would like to use a service I created (with the interface IAuthenticationService ) inside the AppShell of a MAUI app (AppShell.xaml.cs). In other words to do something like this:

public partial class AppShell : Shell

private readonly IAuthenticationService _AuthenticationService;
public AppShell(AuthenticationService authenticationService)
{
    InitializeComponent();
    _AuthenticationService = authenticationService;
}

For the above I added the following code to the App.xaml.cs file

public partial class App : Application
{
    public App(AuthenticationService authenticationService)
    {
        InitializeComponent();
        MainPage = new AppShell(authenticationService);
    }
}

But when I run this, I get the error:

Unable to resolve service for type 'MyApp.Services.AuthenticationService' while attempting to activate 'MyApp.App'.'

Needless to say that I have done the code need in MauiProgram.cs

builder.Services.AddSingleton<IAuthenticationService, AuthenticationService>();

So basically how do I do DI in App.xaml.cs or in AppShell.xaml.cs?


Solution

  • You're passing in the implementation instead of the interface, which is why the dependency cannot get resolved by the dependency container.

    Your code should look like this instead:

    private readonly IAuthenticationService _AuthenticationService;
    
    //note the interface
    public AppShell(IAuthenticationService authenticationService)
    {
      InitializeComponent();
      _AuthenticationService = authenticationService;
    }
    

    and

    public partial class App : Application
    {
        //note the interface
        public App(IAuthenticationService authenticationService)
        {
          InitializeComponent();
          MainPage = new AppShell(authenticationService);
        }
    }