来自 Android 后台服务的 Prism DI 容器

Prism DI container from Android background service

我的应用有一个后台服务,可能 运行 独立于主应用 (HostApduService)。

我如何access/use Prism 的 IContainer 来自这个后台服务?

我知道 IContainer 可从 Xamarin.Forms.Application.Current 获得,请参阅:

https://tutel.me/c/programming/questions/45097342/implement+dependency+injection+in+background+services+in+xamarin+forms+using+prism

但是,在我的情况下,如果服务是 运行 而没有启动应用程序本身,则该应用程序可能不存在。

如果 App.Current 为空,您有几个选项。

1) 在你的后台服务中初始化应用程序的一个新实例:

var app = new App();
app.Container.Resolve<IMyService>();

2) 使用辅助方法,它只注册您想要的内容并创建后台服务所需的容器:

public class App : PrismApplication
{
    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        RegisterBackgroundServices(containerRegistry);
    }

    public static void RegisterBackgroundServices(IContainerRegistry containerRegistry)
    {
        // Register services you need in the Background Service
    }
}

public class MyBackgroundService
{
    IContainerExtension Container { get; }
    public MyBackgroundService()
    {
        // Note: Prism has some non-default Rules in place
        Container = new DryIocContainerExtension(new Container());
        App.RegisterBackgroundServices(Container);
    }
}