Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for hosted services in .NET MAUI apps #2244

Open
Eilon opened this issue Aug 25, 2021 · 24 comments
Open

Add support for hosted services in .NET MAUI apps #2244

Eilon opened this issue Aug 25, 2021 · 24 comments
Labels
area-core-hosting Extensions / Hosting / AppBuilder / Startup Task neither bug nor feature but something that needs to be done in support of either
Milestone

Comments

@Eilon
Copy link
Member

Eilon commented Aug 25, 2021

Look into using hosted services. This would replace the icky IMauiInitializeService that was added in #2137, and also to enable users to use hosted services. MAUI will automatically call StartAsync/StopAsync at the appropriate time. Sadly, this pattern is async-only, whereas in MAUI the call sites are always (or at least almost always) sync. But given that this is app startup/shutdown, doing async-over-sync might be OK (we would block).

This is a follow-up to PR #2137.

Other notes:

@halter73
Copy link
Member

But given that this is app startup/shutdown, doing async-over-sync might be OK (we would block).

I think this is reasonable. That's effectively what happens when a Program.Main() uses the generic host. Even with an async Program.Main(), the compiler synthesizes the real entry point which blocks.

@pjmagee
Copy link

pjmagee commented Sep 30, 2021

Just to clarify my understanding, this would mean once supported i could drop the following icky code I'm using? I pass the IHostEnvironment environment to some wiring code, The maui App assembly is just "HeroesProfile", but i use shared IoC registration. To give some context on how I'm using DI.

 /*
             * Hosted services only works with the Hosting Extensions from .NET
             * Maui does not use the same Hosting service and so we much register them differently depending on how we execute background services.
             * If this is for Maui, we must hook into Application startup and run the services.
             * If this is for Console, .AddHostedService will handle starting the services for us.
             */
            if (environment.ApplicationName.Equals("HeroesProfile.Console"))
            {
                services
                    .AddHostedService<GameSimulator>()
                    .AddHostedService<FileWatchers>()
                    .AddHostedService<OnLaunchReplayProcessor>();
            }
            else
            {
                services
                    .AddSingleton<GameSimulator>()
                    .AddSingleton<FileWatchers>()
                    .AddSingleton<OnLaunchReplayProcessor>();
            }

@Eilon Eilon added the area-core-hosting Extensions / Hosting / AppBuilder / Startup label Sep 30, 2021
@Eilon
Copy link
Member Author

Eilon commented Sep 30, 2021

@pjmagee yeah I think so. If we implement this, there would be proper support for hosted services so all the regular APIs that exist for that would work as expected (starting/stopping those services).

@RayKoopa
Copy link

RayKoopa commented Nov 3, 2021

Dumb question hopefully not too off-topic; what does an IHostedService mean on Android? Will that behave like an Android foreground service or will it only live as long as the MAUI app is running? I want to run an always-on .NET 5 BackgroundService on my Android smartphone and am a little lost figuring out how to utilize MAUI or net6.0-android for that yet.

@Eilon
Copy link
Member Author

Eilon commented Nov 3, 2021

@RayKoopa - This would be for in-app in-proc services. So they would start when the app starts, and dies when the app dies. I'm not sure in Android terminology what that equates to, but it's not a background thing.

@RayKoopa
Copy link

RayKoopa commented Nov 3, 2021

@Eilon Ah alright, I expected it to be "app-wide". I'll try to figure out how to host my Android foreground service then (which is like a "system-wide" background thread with a notification, that has no connection to an app or UI once started). Thanks for the fast reply!

@hflexgrig
Copy link

Any news from this issue?

hflexgrig added a commit to hflexgrig/maui that referenced this issue Dec 9, 2021
@hflexgrig
Copy link

@Eilon Added pull request for this issue #3718

@Eilon
Copy link
Member Author

Eilon commented Dec 9, 2021

@hflexgrig oh wow I'll take a look!

hflexgrig added a commit to hflexgrig/maui that referenced this issue Dec 10, 2021
@hflexgrig
Copy link

@Eilon deleted old one and create new #3724

@obenyaala
Copy link

any status on this feature? Thanks

@ctigrisht
Copy link

will there ever be hosted services?

@kevinchalet
Copy link

kevinchalet commented Jan 19, 2023

FWIW, having native IHostedService support would allow OpenIddict users to use the new OpenIddict.Client.SystemIntegration package on MAUI/WinUI. I posted more information here: openiddict/openiddict-core#1480 (comment).

@JohnHunterACS
Copy link

This kind of addition would definitely make it easier to work with an abstracted service model instead of platform specific service implementations.

@DoubleDBE
Copy link

Any news about this? Currently stuck because of this...

@Eilon
Copy link
Member Author

Eilon commented Mar 15, 2023

This work is not currently planned. Could you manually start the services in MauiProgram or another part of the app? Certainly not ideal, but it could be a reasonable workaround.

kodiakhq bot referenced this issue in sullivanpj/open-system Jun 22, 2023
[![Mend Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com)

This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [Akka.Cluster.Hosting](https://togithub.com/akkadotnet/Akka.Hosting) | nuget | patch | `1.5.4` -> `1.5.8` |

---

### Release Notes

<details>
<summary>akkadotnet/Akka.Hosting</summary>

### [`v1.5.8`](https://togithub.com/akkadotnet/Akka.Hosting/blob/HEAD/RELEASE_NOTES.md#&#8203;158--21-June-2023)

[Compare Source](https://togithub.com/akkadotnet/Akka.Hosting/compare/1.5.7...1.5.8)

-   [Update Akka.NET to 1.5.8](https://togithub.com/akkadotnet/akka.net/releases/tag/1.5.8)
-   [\[Akka.Cluster.Hosting\] PassivateEntityAfter should not override HOCON settings](https://togithub.com/akkadotnet/Akka.Hosting/pull/318)
-   [\[Akka.Hosting\] Set application exit code to -1 if CoordinatedShutdown was caused by cluster down or leave](https://togithub.com/akkadotnet/Akka.Hosting/pull/329)

### [`v1.5.7`](https://togithub.com/akkadotnet/Akka.Hosting/blob/HEAD/RELEASE_NOTES.md#&#8203;157--23-May-2023)

[Compare Source](https://togithub.com/akkadotnet/Akka.Hosting/compare/1.5.6.1...1.5.7)

-   [Update Akka.NET to 1.5.7](https://togithub.com/akkadotnet/akka.net/releases/tag/1.5.7)

### [`v1.5.6.1`](https://togithub.com/akkadotnet/Akka.Hosting/blob/HEAD/RELEASE_NOTES.md#&#8203;1561--17-May-2023)

[Compare Source](https://togithub.com/akkadotnet/Akka.Hosting/compare/1.5.6...1.5.6.1)

-   [Akka.Hosting now throws `PlatformNotSupportedException`](https://togithub.com/akkadotnet/Akka.Hosting/pull/293) when attempting to run on Maui, due to [https://github.com/dotnet/maui/issues/2244](https://togithub.com/dotnet/maui/issues/2244). Maui support will be added in https://github.com/akkadotnet/Akka.Hosting.Maui
-   [make `AkkaHostedService` `public` + `virtual` so it can be extended and customized](https://togithub.com/akkadotnet/Akka.Hosting/pull/306) - advanced feature.

### [`v1.5.6`](https://togithub.com/akkadotnet/Akka.Hosting/blob/HEAD/RELEASE_NOTES.md#&#8203;1561--17-May-2023)

[Compare Source](https://togithub.com/akkadotnet/Akka.Hosting/compare/1.5.5...1.5.6)

-   [Akka.Hosting now throws `PlatformNotSupportedException`](https://togithub.com/akkadotnet/Akka.Hosting/pull/293) when attempting to run on Maui, due to [https://github.com/dotnet/maui/issues/2244](https://togithub.com/dotnet/maui/issues/2244). Maui support will be added in https://github.com/akkadotnet/Akka.Hosting.Maui
-   [make `AkkaHostedService` `public` + `virtual` so it can be extended and customized](https://togithub.com/akkadotnet/Akka.Hosting/pull/306) - advanced feature.

### [`v1.5.5`](https://togithub.com/akkadotnet/Akka.Hosting/blob/HEAD/RELEASE_NOTES.md#&#8203;155--4-May-2023)

[Compare Source](https://togithub.com/akkadotnet/Akka.Hosting/compare/1.5.4.1...1.5.5)

-   [Update Akka.NET to 1.5.5](https://togithub.com/akkadotnet/akka.net/releases/tag/1.5.5)

### [`v1.5.4.1`](https://togithub.com/akkadotnet/Akka.Hosting/blob/HEAD/RELEASE_NOTES.md#&#8203;1541--1-May-2023)

[Compare Source](https://togithub.com/akkadotnet/Akka.Hosting/compare/1.5.4...1.5.4.1)

-   [Add ShardOptions.PassivateIdleEntityAfter option property](https://togithub.com/akkadotnet/Akka.Hosting/pull/290)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Mend Renovate](https://www.mend.io/free-developer-tools/renovate/). View repository job log [here](https://developer.mend.io/github/sullivanpj/open-system).
@samhouts samhouts added the Task neither bug nor feature but something that needs to be done in support of either label Jul 31, 2023
@janseris
Copy link

This work is not currently planned. Could you manually start the services in MauiProgram or another part of the app? Certainly not ideal, but it could be a reasonable workaround.

Does this really work in Android when screen is switched off?

@bdovaz
Copy link

bdovaz commented Sep 16, 2024

Any updates?

@symbiogenesis
Copy link
Contributor

Need this

@mariuszdybala
Copy link

I'm also looking forward to seeing it in MAUI. In the meantime, what is the best practice for MAUI to have background tasks that periodically perform REST requests to get data?

@pjmagee
Copy link

pjmagee commented Oct 17, 2024

I'm also looking forward to seeing it in MAUI. In the meantime, what is the best practice for MAUI to have background tasks that periodically perform REST requests to get data?

I think you can take the concept of a hosted service but you need to activate those in the Maui Startup event. that's basically the best workaround we have, not sure the impact on different devices though.

@Haukinger
Copy link

Hosted services will run while the app is active in the foreground only, right?

@symbiogenesis
Copy link
Contributor

symbiogenesis commented Oct 17, 2024

I'm also looking forward to seeing it in MAUI. In the meantime, what is the best practice for MAUI to have background tasks that periodically perform REST requests to get data?

I use a singleton service that initializes a dispatcher timer on a certain interval, which is wired up in the constructor of the service.

A hosted service would be better, for a number of reasons. But that is adequate-ish.

i.e.

.AddSingleton<ISyncService, SyncService>()

and

internal sealed class SyncService : ISyncService, IDisposable
{
    private readonly IDispatcherTimer syncTimer;

    public SyncService()
    {
        // Set a timer to execute the sync on an interval
        this.syncTimer = Application.Current.Dispatcher.CreateTimer();
        this.syncTimer.Interval = TimeSpan.FromMinutes(2);
        this.syncTimer.Tick += this.OnSyncTimerElapsed;
    }

    private void OnSyncTimerElapsed(object? sender, EventArgs e)
    {
        // Do Stuff Here
    }
}

@illuminat3
Copy link

Any update?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-core-hosting Extensions / Hosting / AppBuilder / Startup Task neither bug nor feature but something that needs to be done in support of either
Projects
None yet
Development

No branches or pull requests