Reputation: 2640
I've turned on connection resiliency in Entity Framework Core:
services.AddDbContext<MyDbContext>( options =>
options.UseSqlServer(Configurations["ConnectionString"]),
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.EnableRetryOnFailure(
maxRetryCount: 10,
maxRetryDelay: TimeSpan.FromSeconds(5),
errorNumbersToAdd: null);
});
Now I would like to create some unit test to prove this is actually working. Is it possible to do something like that?
The InMemoryDbContext
doesn't seem to have the EnableRetryOnFailure
method and the most similar test I could find was in EF6:
https://thedatafarm.com/data-access/testing-out-the-connection-resiliency-feature-into-ef6/
(and it's kinda complex to follow)
As some additional info i'm using SQL server 2017 and Entity Framework Core 2.2.0, when testing manually if I take the database offline it fails instantly.
Am i testing it wrong or i'm missing something to set this up properly?
Upvotes: 7
Views: 3172
Reputation: 2640
Jeroen Mostert answered this in the comments:
If by "taking the database offline" you literally mean setting the database state to OFFLINE, the failure is expected -- that's not one of the conditions resiliency guards against, as it is not a transient condition that would most likely resolve itself in time. If the server is up but the database was explicitly set offline, you'll immediately get that back as an error -- adding retry for that, if desired, is up to your application. To test connection resiliency, you have to take down the server itself -- i.e. shut down SQL Server (or firewall port 1433, same effect).
Incidentallly, the errorNumbersToAdd property should allow you to mark "database is offline" as a transient error, if so desired -- the error number is 942. Use this only if it makes sense in production as well -- otherwise, for testing, it makes more sense to add 50000, the error number of a custom RAISERROR (e.g. RAISERROR('This is a transient error!', 11, 0)), which is easy to inject in queries. Don't use that in production either, of course, since most custom errors should not be blindly retried -- it makes more sense to use something like Polly for that.
That seems to be the best explanation.
Upvotes: 3