Registering the same singleton for multiple interfaces in IOC

I have a service that should be able to handle my own assets and attribute types, so I have a main service in my PCL called BaseThemeService that implements the IThemeService interface. I need to have access to some attributes from the main PCL, so it implements IThemeService from the main PCL.

Within each platform project, I have a ThemeService class that implements IDroidThemeService and extends BaseThemeService . Then I register IDroidThemeService singleton in the manual configuration of each project.

This works, except that now there are 2 instances of BaseThemeService . 1 registered for IThemeService for the kernel, and 1 registered for IDroidThemeService for the platform.

To get around this, I will build it myself and then register it accordingly:

 protected override void InitializeFirstChance() { ThemeService themeService = new ThemeService(Mvx.Resolve<IMvxJsonConverter>(), Mvx.Resolve<IMvxResourceLoader>()); Mvx.RegisterSingleton<IDroidThemeService>(themeService); Mvx.RegisterSingleton<IThemeService>(themeService); base.InitializeFirstChance(); } 

It seems that it should work, but this does not happen, since the services IMvxJsonConverter and IMvxResourceLoader are not registered yet.

In the MvvmCross documentation, I see that automatic loading using a lazy design will register a service with all interfaces implemented. Is there a way to use this feature here to unregister manually?


Answer

 protected override void InitializeFirstChance() { Mvx.RegisterSingleton<IDroidThemeService>(GetThemeService); Mvx.RegisterSingleton<IThemeService>(GetThemeService); base.InitializeFirstChance(); } private DroidThemeService DroidSingletonService = null; private DroidThemeService GetThemeService() { if (DroidSingletonService == null) { DroidSingletonService = Mvx.IocConstruct<DroidThemeService>(); } return DroidSingletonService; } 

This is the final decision. I know that RegisterAsLazySingleton trying to solve this problem automatically, so I will update again if I find a way to implement this, a little cleaner.

+6
source share
1 answer

You can register a factory for a singleton, which can produce a singleton manually and return it when someone wants to call it. See Lazy Singleton Registration Documents

 ThemeService singletonService = null; private ThemeService GetThemeService() { if (singletonService == null) { singletonService = new ThemeService(Mvx.Resolve<IMvxJsonConverter>(), Mvx.Resolve<IMvxResourceLoader>()); } return singletonService; } protected override void InitializeFirstChance() { Mvx.RegisterSingleton<IDroidThemeService>(GetThemeService); Mvx.RegisterSingleton<IThemeService>(GetThemeService); base.InitializeFirstChance(); } 

Depending on your situation, the field and method may be static.

+4
source

Source: https://habr.com/ru/post/983234/


All Articles