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

Fro*_*iwi 3 prism xamarin.android xamarin.forms

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

如何从此后台服务访问/使用 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

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

Dan*_* S. 5

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

1) 在你的后台服务中初始化一个新的 App 实例:

var app = new App();
app.Container.Resolve<IMyService>();
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)