Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to add hangfire in my .net core project.It creates Hangfire database but throws an exception whenever I try to add a recurring or background job

Hangfire.BackgroundJobClientException: Background job creation failed. See inner exception for details. ---> System.InvalidCastException: Unable to cast object of type 'System.Data.SqlClient.SqlConnection' to type 'Microsoft.Data.SqlClient.SqlConnection'.

Here is my code

services.AddHangfire(config =>
        config.SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
        .UseSimpleAssemblyNameTypeSerializer()
        .UseDefaultTypeSerializer()
        .UseSqlServerStorage(Configuration.GetConnectionString("Hangfire"),
        new Hangfire.SqlServer.SqlServerStorageOptions
        {
            SchemaName = "Test"
        }));
        services.AddHangfireServer();

        app.UseHangfireDashboard();
        backgroundJobClient.Enqueue(() => Console.WriteLine("Hello Hanfire job!"));

I thought there might be some issue with the version of Hangfire packages I am using so I also tried previous versions but it did not make any difference. One suggestion which I have found is to replace System.Data.SqlClient library with Microsoft.Data.SqlClient but it is not possible because Hangfire.SqlServer requires System.Data.SqlClient.

question from:https://stackoverflow.com/questions/66054656/hangfire-background-job-creation-failed-with-invalidcastexception

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
807 views
Welcome To Ask or Share your Answers For Others

1 Answer

I am able to resolve the issue by using Microsoft.Data.SqlClient instead of System.Data.SqlClient like this

.UseSqlServerStorage(() => new Microsoft.Data.SqlClient.SqlConnection(Configuration.GetConnectionString("Hangfire"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...