Last active
February 9, 2026 19:41
-
-
Save afscrome/85ce721283b0f719c7de6e48470b8397 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // A crude Event subscriber that tries to start docker desktop automatically if it's not running. | |
| // use it with `builder.Services.AddEventingSubscriber<DockerAutoStartSubscriber>();` | |
| internal class DockerAutoStartSubscriber : IDistributedApplicationEventingSubscriber | |
| { | |
| public Task SubscribeAsync(IDistributedApplicationEventing eventing, DistributedApplicationExecutionContext executionContext, CancellationToken cancellationToken) | |
| { | |
| eventing.Subscribe<BeforeStartEvent>((evt, ct) => | |
| { | |
| if (evt.Model.Resources.Where(x => x.IsContainer()).Any()) | |
| { | |
| _ = Task.Run(WatchForRuntimeUnavaialble, ct); | |
| } | |
| return Task.CompletedTask; | |
| async Task WatchForRuntimeUnavaialble() | |
| { | |
| var resourceNotificationService = evt.Services.GetRequiredService<ResourceNotificationService>(); | |
| await foreach (var update in resourceNotificationService.WatchAsync(ct)) | |
| { | |
| if (!update.Resource.IsContainer()) | |
| { | |
| continue; | |
| } | |
| if (update.Snapshot.State == KnownResourceStates.Running || KnownResourceStates.TerminalStates.Contains(update.Snapshot.State?.Text)) | |
| { | |
| // If a container reaches any of these states, the runtime is available | |
| // Stop watching | |
| return; | |
| } | |
| if (update.Snapshot.State == KnownResourceStates.RuntimeUnhealthy) | |
| { | |
| var logger = evt.Services.GetRequiredService<ILogger<DockerAutoStartSubscriber>>(); | |
| logger.LogDebug("Trying to auto start docker"); | |
| _ = Task.Run(async () => | |
| { | |
| try | |
| { | |
| using var process = Process.Start(new ProcessStartInfo | |
| { | |
| FileName = "docker", | |
| ArgumentList = { "desktop", "start", "--detach" }, | |
| CreateNoWindow = true, | |
| WindowStyle = ProcessWindowStyle.Hidden, | |
| UseShellExecute = true | |
| }); | |
| if (process == null) | |
| { | |
| return; | |
| } | |
| await process.WaitForExitAsync(ct); | |
| if (process.ExitCode == 0) | |
| { | |
| logger.LogInformation("Starting docker..."); | |
| } | |
| else | |
| { | |
| logger.LogWarning("Attempt to auto start docker failed with ExitCode {ExitCode}", process.ExitCode); | |
| } | |
| } | |
| catch (Exception ex) | |
| { | |
| logger.LogWarning(ex, "Unable to start docker automatically. Please start it manually."); | |
| } | |
| }, ct); | |
| return; | |
| } | |
| } | |
| } | |
| }); | |
| return Task.CompletedTask; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment