Giuseppe Terrasi
Giuseppe Terrasi

Reputation: 489

ASP.NET Core : intercept DbContext connection timeout exception inside controller

I have an ASP.NET Core MVC application where I inject a DbContext into a controller. I want to know if there is a way to intercept the connection timeout exception while constructing the DbContext returning a specific error response code.

I noticed that the exception is thrown inside the method AddDbContext in the Startup class:

services.AddDbContext<MyDbContext>(options =>
        {
            options.UseMySql(Configuration.GetConnectionString("DefaultConnection"),
                ServerVersion.AutoDetect(Configuration.GetConnectionString("DefaultConnection")), o => 
                {
                    o.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery);
                });
        });

EDIT: Could the exception be thrown from the AutoDetect option which opens a connection to the DB to retrieve its version? I'm using the Pomelo.EntityFrameworkCore.MySql NuGet package, version 5.0.0

Thanks

Upvotes: 0

Views: 1036

Answers (1)

lauxjpn
lauxjpn

Reputation: 5254

If you want to use the ServerVersion.AutoDetect() method to automatically get your database server version, then you usually want to query it only once on application startup and then reuse it in your UseMySql() calls:

var connectionString = Configuration.GetConnectionString("DefaultConnection");
var serverVersion = ServerVersion.AutoDetect(connectionString);

services.AddDbContext<MyDbContext>(options => options
    .UseMySql(connectionString, serverVersion, o => o
        .UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery)));

In addition, if you want some retry logic for ServerVersion.AutoDetect(), take a look at Missing retry policy for ServerVersion.AutoDetect() #1368.

You can also explicitly set your server version by using the MySqlServerVersion or MariaDbServerVersion classes.

Could the exception be thrown from the AutoDetect option which opens a connection to the DB to retrieve its version? I'm using the Pomelo.EntityFrameworkCore.MySql NuGet package, version 5.0.0

Yes, that is where the exception gets thrown in your case. Otherwise, the exception would be thrown when the DbContext first needs the database connection (usually when you execute your first query), which is sometime later after calling AddDbContext().

Upvotes: 1

Related Questions