migrationmauiwinui-3migrate

How to Properly Register and Access Dependency Services in .NET MAUI Multi-Project App with WinUI3


I'm building a .NET MAUI multi-project app with only WinUI 3 support. My solution consists of three projects:

MauiApp - Contains all XAML and UI-related code. DataCore - Contains managers, enums, and entities. WinUI3 - Handles database calls, logging services, picture picker, and other dependency services. I'm facing an issue with accessing a logging service from the mauiapp project. I created an ILoggingService interface in the mauiapp project and implemented it in the winui3 project. However, when I try to fetch the logging service, I always receive null.

In my previous Xamarin.Forms project, I handled this in App.xaml.cs for UWP like this, and it worked fine:(it is now also working fine in maui)

DependencyService.Register<ILoggingService, LoggingService>(); DependencyService.Register<IPicturePicker, PicturePicker>();

For .NET MAUI, I moved this logic to MauiProgram.cs in the winui3 project using: builder.Services.AddSingleton<ILoggingService, LoggingService>();

But this still isn't working, and the logging service, or picturepicker remains null when accessed in mauiapp.

How can I correctly register and access dependency services (such as ILoggingService, IPicturePicker) across different projects in a .NET MAUI multi-project solution? Specifically, how should I set this up so that services defined in the WinUI3 project are accessible in the MauiApp project?


Solution

  • In Xamarin Forms, if you want to invoke native platform functionality from shared code, you may use Xamarin.Forms DependencyService. Now in MAUI, either using Conditional compilation or Partial classes and methods can help you use native code.

    If you use Conditional compilation, just try

    #if Windows
            //you may invoke the platform code here
    #endif
    

    Or you may use Partial classes and methods, then you should Define the cross-platform API and Implement the API per platform.

    For more info, please refer to Invoke platform code.