Search code examples
xamarinxamarin.formsprismprism-7

Register and Resolve DI containers in Prism 7 - Xamarin Forms


I'm using prism 7 for my new xamarin forms application.I have gone through this document.

I have couple of questions:

  1. There are few DI interfaces I register after the app starts. We can use IContainerRegistry in app.xaml.cs to register but if we want to register or resolve in other pages, is there any way to get do it other that saving the IContainerRegistry and IContainerRegistry instance from app.xaml.cs and using it where ever we want?

  2. To register a type the syntax is :

    ContainerRegistry.RegisterInstance<ITextService>(new TextService());

But how can we register a singleton? I saw few examples but I did not really understand how to do it? can anyone please show an example?

UPDATE:

To register a singleton, The syntax seems like
containerRegistry.RegisterSingleton<ILoggerFacade, EmptyLogger>(); but if we just pass the type without creating an instance ( in this case, the instance of EmptyLogger), how can we use properly register them?


Solution

  • To register a type the syntax is: ContainerRegistry.RegisterInstance<ITextService>(new TextService());

    this registers an instance not a type, btw, to register a type do ContainerRegistry.Register<IAnInterface, SomeImplementation>();

    But how can we register a singleton?

    ContainerRegistry.RegisterSingleton<ITextService, TextService>(); does this, and btw, an instance is a singleton by nature (because the di container always has to inject the one instance you registered as it cannot create new instances on its own)

    is there any way to get do it other that saving the IContainerRegistry and IContainerRegistry instance from app.xaml.cs and using it where ever we want?

    I recommend registering everything in one place rather than scattering registrations all over the project. But if you're determined, you can have IContainerRegistry injected anywhere and register your stuff.