Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
802 views
in Technique[技术] by (71.8m points)

asp.net core - Hangfire Background job creation failed with InvalidCastException

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

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

1 Reply

0 votes
by (71.8m points)

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"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...