[英]Xamarin.Forms Prism: Android dependency injection of platform-specific service
Im trying to inject a Android- and iOS-specific service, but on Android I get an error in App.xaml.cs
about it not being able to resolve the parameter for LoginService
我试图注入特定于Android和iOS的服务,但是在Android上,我在App.xaml.cs
收到错误消息,提示它无法解析LoginService
的参数
My App.xaml.cs
: 我的App.xaml.cs
:
protected override void RegisterTypes()
{
Container.RegisterTypeForNavigation<NavigationPage>();
Container.RegisterTypeForNavigation<MainPage>();
Container.RegisterTypeForNavigation<MapsPage>();
Container.RegisterInstance<ILoginService>(new LoginService(Container.Resolve<IClsDkwsService>()));
}
My MainActivity.cs
: 我的MainActivity.cs
:
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.tabs;
ToolbarResource = Resource.Layout.toolbar;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App(new AndroidInitializer()));
}
}
public class AndroidInitializer : IPlatformInitializer
{
public void RegisterTypes(IUnityContainer container)
{
container.RegisterInstance<IClsCryptoService>(new Cls_crypto());
container.RegisterInstance<IClsDkwsService>(new Cls_dkws());
}
}
It looks like AndroidInitializer.RegisterTypes()
is called after App.RegisterTypes()
. 它看起来像AndroidInitializer.RegisterTypes()
后调用App.RegisterTypes()
I would like to avoid registering LoginService
in each platform. 我想避免在每个平台上注册LoginService
。 How do I ensure all platform-specific services are registered in App.xaml.cs
? 如何确保在App.xaml.cs
中注册了所有特定于平台的服务?
Instead of trying to manually create instances of these dependencies, use the features of the DI container. 与其尝试手动创建这些依赖项的实例,不如使用DI容器的功能。 You can register a type as a singleton in Unity by using 您可以使用以下方法在Unity中将类型注册为单例
Container.RegisterType<IMyService, MyService>(new ContainerControlledLifetimeManager());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.