Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transient Failure handling in .net core 2.1 MVC for MySQL Database

services.AddDbContext<MyContext>(options =>
{
    options.UseSqlServer(mysqlConnection,
    sqlServerOptionsAction: sqlOptions =>
    {
        sqlOptions.EnableRetryOnFailure(
        maxRetryCount: 10,
        maxRetryDelay: TimeSpan.FromSeconds(30),
        errorNumbersToAdd: null);
    });
});

I found this code snippet at:

https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/implement-resilient-applications/implement-resilient-entity-framework-core-sql-connections

My DB is MySQL 5.7

I changed the above code to :

enter image description here

That means EnableRetryOnFailure is not available for MySQL DB. How do i set the retry, delay etc.. policies now?

Also if i try to set the ExecutionStrategy function i get this:

enter image description here

Then i tried Create my own Strategy using:

public class MyStrategy: ExecutionStrategy
{
   ......
}

but how to use this class now?

like image 381
ABC DEF Avatar asked Mar 30 '19 14:03

ABC DEF


2 Answers

There is a library for this: https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql

Setup steps:

  1. Donwload Pomelo.EntityFrameworkCore.MySql from NuGet.

  2. Add this using to your class:

    using Pomelo.EntityFrameworkCore.MySql.Infrastructure;

  3. Add this to your ConfigureServices method:

    services.AddDbContextPool<ApplicationDbContext>( 
    options => options.UseMySql("Server=localhost;Database=ef;User=root;Password=123456;",
    
        mySqlOptions =>
        {
            mySqlOptions.ServerVersion(new Version(5, 7, 17), ServerType.MySql)
            .EnableRetryOnFailure(
            maxRetryCount: 10,
            maxRetryDelay: TimeSpan.FromSeconds(30),
            errorNumbersToAdd: null); 
        }
    ));
    
like image 74
hujtomi Avatar answered Oct 03 '22 02:10

hujtomi


If you're using .NET 5, to avoid does not contain a definition for 'ServerVersion' you can use the following:

services.AddDbContext<AppDbContext>(options =>
{
    string connectionString = AppConfig.Configuration.GetConnectionString("DefaultConnection");
    options.UseMySql(connectionString,
        ServerVersion.AutoDetect(connectionString),
        mySqlOptions =>
            mySqlOptions.EnableRetryOnFailure(
                maxRetryCount: 10,
                maxRetryDelay: TimeSpan.FromSeconds(30),
                errorNumbersToAdd: null);
        );
});
like image 20
Sir Crusher Avatar answered Oct 03 '22 03:10

Sir Crusher