How do you use Xamarin Shiny Dependency Injection

Viewed 144

I'm writing a cross platform Xamarin background application and want to use Shiny.

I have got a service interface and platform specific concrete implementations of the class.

I'm sure its something simple but the piece of the puzzle I am missing is how to register the interface in the Shiny DI container so that the correct platform specific implementation is used.

If I was doing this without Shiny I would have my own DI container in the App class and initialise that from each platform. With Shiny, I only seem to have the ShinyStart class where I can get to the services collection but that does not have access to the concrete classes.

I have looked into Shiny modules but cannot figure out from the documentation how they get around the issue either

How do I get access to the Shiny DI service container from within platform specific code so I can register the correct concrete class against the interface?

Regards Brian

1 Answers

If anybody else is interested in this I found the answer buried in the shiny code. You have to define a MainApplication class and use RegeisterPlatformServices.

public partial class MainApplication : global::Android.App.Application
{
    public MainApplication(IntPtr handle, JniHandleOwnership transfer) : 
    base(handle, transfer) {}

    public override void OnCreate()
    {
        this.ShinyOnCreate(new global::ElevateNfc.ShinyStartup
        {
            RegisterPlatformServices = services =>
            {
                services.AddSingleton<IManager, Manager>();
            }
        });
        global::Xamarin.Essentials.Platform.Init(this);
        base.OnCreate();
    }
}
Related