我的应用程序有一个可以独立于主应用程序 (HostApduService) 运行的后台服务。
如何从此后台服务访问/使用 Prism 的 IContainer?
我知道 IContainer 可从 Xamarin.Forms.Application.Current 获得,请参阅:
但是,在我的情况下,如果服务在没有启动应用程序本身的情况下运行,则应用程序可能不存在。
最佳答案
如果 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);
}
}
关于xamarin.forms - 来自 Android 后台服务的 Prism DI 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53014936/