Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prism DI container from Android background service

My app has a background service that may be run independently of the main app (HostApduService).

How can I access/use Prism's IContainer from this background service?

I am aware that IContainer is available from Xamarin.Forms.Application.Current, see:

https://tutel.me/c/programming/questions/45097342/implement+dependency+injection+in+background+services+in+xamarin+forms+using+prism

However it is possible in my case that the App doesn't exist, if the service is run without bringing up the app itself.

like image 304
FrozenKiwi Avatar asked Oct 16 '25 22:10

FrozenKiwi


1 Answers

There are a couple options for you if App.Current is null.

1) in your background service initialize a new instance of the App:

var app = new App();
app.Container.Resolve<IMyService>();

2) use a helper method that only registers what you want and create the container you need for your background service:

public class App : PrismApplication
{
    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        RegisterBackgroundServices(containerRegistry);
    }

    public static void RegisterBackgroundServices(IContainerRegistry containerRegistry)
    {
        // Register services you need in the Background Service
    }
}

public class MyBackgroundService
{
    IContainerExtension Container { get; }
    public MyBackgroundService()
    {
        // Note: Prism has some non-default Rules in place
        Container = new DryIocContainerExtension(new Container());
        App.RegisterBackgroundServices(Container);
    }
}
like image 182
Dan Siegel Avatar answered Oct 19 '25 12:10

Dan Siegel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!