Reputation: 1479
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
My 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
:
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()
. I would like to avoid registering LoginService
in each platform. How do I ensure all platform-specific services are registered in App.xaml.cs
?
Upvotes: 1
Views: 1107
Reputation:
Instead of trying to manually create instances of these dependencies, use the features of the DI container. You can register a type as a singleton in Unity by using
Container.RegisterType<IMyService, MyService>(new ContainerControlledLifetimeManager());
Upvotes: 3