0

我试图弄清楚如何在 MauiBlazor 项目中共享 Maui 和 Blazor 之间的服务。目标是能够使用相同的单例,而无需将这些单例的静态实例存储在某处。

4

1 回答 1

1

虽然在未来的版本中这可能是一种更方便的方式,但我从Maui.Plugins.PageResolver的一些灵感中找到了一种方法。与问题maui#792相关

在 Github 上添加了一个 nuget + 工作示例应用程序

这是我解决它的方法:

1.为服务提供者创建一个仓库

public static class Resolver
{
    private static IServiceProvider _serviceProvider;
    public static IServiceProvider ServiceProvider => _serviceProvider ?? throw new Exception("Service provider has not been initialized");

    /// <summary>
    /// Register the service provider
    /// </summary>
    public static void RegisterServiceProvider(IServiceProvider sp)
    {
        _serviceProvider = sp;
    }
    /// <summary>
    /// Get service of type <typeparamref name="T"/> from the service provider.
    /// </summary>
    public static T Resolve<T>() where T : class
        => ServiceProvider.GetRequiredService<T>();
}

2.应用启动的扩展方法

public static void UseResolver(this MauiApp app)
{
    Resolver.RegisterServiceProvider(app.Services);
}

或者为了避免依赖毛伊岛:

public static void UseResolver(this IServiceProvider sp)
{
    Resolver.RegisterServiceProvider(sp);
}

3a。样品测试服务

public class TestSingletonService
{
    private static int _staticIndex = 0;
    public int Index {  get; set; }

    public TestSingletonService()
    {
        Index = _staticIndex++;
    }
}

3b。注册服务集合

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder
            .RegisterBlazorMauiWebView()
            .UseMauiApp<App>()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
            });

        builder.Services.AddBlazorWebView();
        builder.Services.AddSingleton<WeatherForecastService>();

        // Register any other service / ViewModel / Page here
        builder.Services.AddSingleton<TestSingletonService>();

        // Pre-build the app
        var app = builder.Build();
        // Intercept and register the ServiceProvider
        app.UseResolver();
        // Or to avoid Maui dependency
        // app.Services.UseResolver();
        // Return the app as usual
        return app;
    }
}

4a。将其用作毛伊岛的工厂

Resolver.ServiceProvider.GetRequiredService<TestSingletonService>();
Console.WriteLine($"Instance number {TestSingletonService.Index}");

4b。服务实例将与您的 Blazor@inject服务共享。

@inject TestSingletonService tester
Instance number @(tester.Index).
于 2021-09-26T08:43:49.977 回答