From 31ccd93b0d3b1814ed19a61b960929d6799b8221 Mon Sep 17 00:00:00 2001 From: Developer 02 Date: Mon, 3 Feb 2025 16:22:41 +0100 Subject: [PATCH] refactor(AuthClient): Enhance AuthClient with lazy initialization and connection error handling - Replaced immediate connection start with lazy initialization via Lazy>. - Added IsConnected and ConnectionError properties to track connection status and errors. - Introduced TryStartAsync method to safely attempt connection startup without throwing exceptions. --- DigitalData.Auth.Abstractions/IAuthClient.cs | 2 ++ DigitalData.Auth.Client/AuthClient.cs | 37 +++++++++++++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/DigitalData.Auth.Abstractions/IAuthClient.cs b/DigitalData.Auth.Abstractions/IAuthClient.cs index f147d23..ca2be02 100644 --- a/DigitalData.Auth.Abstractions/IAuthClient.cs +++ b/DigitalData.Auth.Abstractions/IAuthClient.cs @@ -3,4 +3,6 @@ public interface IAuthClient : IAuthClientHandler { Task StartAsync(); + + Task TryStartAsync(); } \ No newline at end of file diff --git a/DigitalData.Auth.Client/AuthClient.cs b/DigitalData.Auth.Client/AuthClient.cs index 04b4623..a220fa8 100644 --- a/DigitalData.Auth.Client/AuthClient.cs +++ b/DigitalData.Auth.Client/AuthClient.cs @@ -9,6 +9,8 @@ public class AuthClient : IAuthClient { private readonly HubConnection _connection; + private readonly Lazy> _lazyInitiator; + private readonly ILogger? _logger; private readonly ClientParams _params; @@ -24,9 +26,42 @@ public class AuthClient : IAuthClient _logger = logger; _params = paramsOptions.Value; + + _lazyInitiator = new(async () => + { + try + { + await _connection.StartAsync(); + IsConnected = true; + return true; + } + catch(Exception ex) + { + ConnectionError = ex; + throw; + } + }); } - public async Task StartAsync() => await _connection.StartAsync(); + public bool IsConnected { get; private set; } = false; + + public Exception? ConnectionError { get; private set; } + + public bool IsConnectionFailed => ConnectionError is not null; + + public async Task StartAsync() => await _lazyInitiator.Value; + + public async Task TryStartAsync() + { + try + { + return await _lazyInitiator.Value; + } + catch + { + return false; + } + } public Task ReceiveMessageAsync(string user, string message) => Task.Run(() => _params.Events.OnMessageReceived(user, message, _logger)); } \ No newline at end of file