refactor(AuthClient): Enhance AuthClient with lazy initialization and connection error handling
- Replaced immediate connection start with lazy initialization via Lazy<Task<bool>>. - Added IsConnected and ConnectionError properties to track connection status and errors. - Introduced TryStartAsync method to safely attempt connection startup without throwing exceptions.
This commit is contained in:
parent
48970a1e13
commit
31ccd93b0d
@ -3,4 +3,6 @@
|
||||
public interface IAuthClient : IAuthClientHandler
|
||||
{
|
||||
Task StartAsync();
|
||||
|
||||
Task<bool> TryStartAsync();
|
||||
}
|
||||
@ -9,6 +9,8 @@ public class AuthClient : IAuthClient
|
||||
{
|
||||
private readonly HubConnection _connection;
|
||||
|
||||
private readonly Lazy<Task<bool>> _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<bool> TryStartAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
return await _lazyInitiator.Value;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public Task ReceiveMessageAsync(string user, string message) => Task.Run(() => _params.Events.OnMessageReceived(user, message, _logger));
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user