Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading