1+ using System ;
2+ using System . Data ;
3+ using System . Threading ;
4+ using Shuttle . Core . Contract ;
5+
6+ namespace Shuttle . Core . Data
7+ {
8+ public static class DatabaseContextFactoryExtensions
9+ {
10+ public static bool IsAvailable ( this IDatabaseContextFactory databaseContextFactory ,
11+ CancellationToken cancellationToken , int retries = 4 , int secondsBetweenRetries = 15 )
12+ {
13+ Guard . AgainstNull ( databaseContextFactory , nameof ( databaseContextFactory ) ) ;
14+
15+ return IsAvailable ( ( ) =>
16+ {
17+ using ( databaseContextFactory . Create ( ) )
18+ {
19+ }
20+ } , cancellationToken , retries , secondsBetweenRetries ) ;
21+ }
22+
23+ public static bool IsAvailable ( this IDatabaseContextFactory databaseContextFactory , string name ,
24+ CancellationToken cancellationToken , int retries = 4 , int secondsBetweenRetries = 15 )
25+ {
26+ Guard . AgainstNull ( databaseContextFactory , nameof ( databaseContextFactory ) ) ;
27+
28+ return IsAvailable ( ( ) =>
29+ {
30+ using ( databaseContextFactory . Create ( name ) )
31+ {
32+ }
33+ } , cancellationToken , retries , secondsBetweenRetries ) ;
34+ }
35+
36+ public static bool IsAvailable ( this IDatabaseContextFactory databaseContextFactory , string providerName , IDbConnection dbConnection ,
37+ CancellationToken cancellationToken , int retries = 4 , int secondsBetweenRetries = 15 )
38+ {
39+ Guard . AgainstNull ( databaseContextFactory , nameof ( databaseContextFactory ) ) ;
40+
41+ return IsAvailable ( ( ) =>
42+ {
43+ using ( databaseContextFactory . Create ( providerName , dbConnection ) )
44+ {
45+ }
46+ } , cancellationToken , retries , secondsBetweenRetries ) ;
47+ }
48+
49+ public static bool IsAvailable ( this IDatabaseContextFactory databaseContextFactory , string providerName , string connectionString ,
50+ CancellationToken cancellationToken , int retries = 4 , int secondsBetweenRetries = 15 )
51+ {
52+ Guard . AgainstNull ( databaseContextFactory , nameof ( databaseContextFactory ) ) ;
53+
54+ return IsAvailable ( ( ) =>
55+ {
56+ using ( databaseContextFactory . Create ( providerName , connectionString ) )
57+ {
58+ }
59+ } , cancellationToken , retries , secondsBetweenRetries ) ;
60+ }
61+
62+ private static bool IsAvailable ( Action action , CancellationToken cancellationToken , int retries = 4 , int secondsBetweenRetries = 15 )
63+ {
64+ var attempt = 0 ;
65+
66+ do
67+ {
68+ try
69+ {
70+ action . Invoke ( ) ;
71+
72+ break ;
73+ }
74+ catch
75+ {
76+ attempt ++ ;
77+
78+ if ( attempt < retries )
79+ {
80+ var wait = DateTime . Now . AddSeconds ( secondsBetweenRetries ) ;
81+
82+ while ( ! cancellationToken . IsCancellationRequested && DateTime . Now < wait )
83+ {
84+ Thread . Sleep ( 250 ) ;
85+ }
86+ }
87+ }
88+ } while ( attempt < retries ) ;
89+
90+ return attempt <= retries ;
91+ }
92+ }
93+ }
0 commit comments