Search code examples
androidios.netcross-platformmaui

Cannot reference platform-specific services in .NET MAUI project


I am working on a .NET MAUI application, and I am having trouble referencing platform-specific services in my main project. I have created an interface IFirebaseAuthService in the DisApp24.Services namespace, and I have implemented this interface in the FirebaseAuthService_Android and FirebaseAuthService_iOS classes within their respective Platforms\Android\Services and Platforms\iOS\Services folders.

However, when I try to register these platform-specific services in the MauiProgram.cs file, the compiler cannot find the platform-specific classes.

Here is my MauiProgram.cs code:

using DisApp24.Services;
using Microsoft.Extensions.DependencyInjection;

namespace DisApp24
{
    public static class MauiProgram
    {
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();

            // Register platform-specific services.
#if __ANDROID__
            builder.Services.AddSingleton<IFirebaseAuthService, DisApp24.Services.FirebaseAuthService_Android>();
#elif __IOS__
            builder.Services.AddSingleton<IFirebaseAuthService, DisApp24.Services.FirebaseAuthService_iOS>();
#endif

            // ...other configurations...

            return builder.Build();
        }
    }
}

I have tried the following approaches to fix this issue:

  • Changing the namespaces of the platform-specific implementations to match the main projects namespace.

  • Manually adding references to the platform-specific implementations in the .csproj file of the main project.

  • Creating a completely new Project where I reproduced the Code, but the error stays the same

Unfortunately, none of these solutions worked, and the issue persists. It seems that the main project cannot reference the Android or iOS projects for some reason. How can I correctly reference and register these platform-specific services in my .NET MAUI application?


Solution

  • About reference platform-specific services in .NET MAUI project:

    Way1 :

    You can refer to official doc: Invoke platform code. It also provides code sample: InvokePlatformCodeDemos.

    Way2 :

    I searched for information about this and found this video by Gerald Versluis: Platform-Specific Code in .NET MAUI Using Dependency Injection. The solution he provides is concise and clear.

    MauiAppBuilder.Services.AddTransient<TService, TImplementation>(IServiceCollection)
    

    And it puts services on a specific platform under the same namespace:

    namespace yourProjectName.Platforms