我正在开发一个 Asp.Net 项目,我试图为后台作业添加“Hangfire”库。我已经根据 daccummentation 安装了所有必需的软件包,并创建了测试数据库。
我还在 Global.asax.vb 中添加了所需的启动方法(必须从示例中给出的 C# 转换为 VB.net),所以我的文件如下所示:
Imports Hangfire
Imports Hangfire.SqlServer
Public Class Global_asax
Inherits HttpApplication
Sub Application_Start(sender As Object, e As EventArgs)
' Fires when the application is started
Try
HangfireAspNet.Use(GetHangfireServers)
Catch ex As Exception
Debug.Assert(False, "Not Yet Ready")
End Try
End Sub
Private Iterator Function GetHangfireServers() As IEnumerable(Of IDisposable)
GlobalConfiguration.Configuration.SetDataCompatibilityLevel(CompatibilityLevel.Version_170).UseSimpleAssemblyNameTypeSerializer().UseRecommendedSerializerSettings().UseSqlServerStorage("Data Source=xxx,00000;Initial Catalog=xxx;User ID=xxx;Password=xxx", New SqlServerStorageOptions With {
.CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
.SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
.QueuePollInterval = TimeSpan.Zero,
.UseRecommendedIsolationLevel = True,
.DisableGlobalLocks = True
})
Yield New BackgroundJobServer()
End Function
End Class
还有
HangfireAspNet.Use(GetHangfireServers)
行抛出下一个异常:
无法将类型“VB$StateMachine_6_GetHangfireServers”的对象转换为类型“System.Func
1[System.IDisposable]]1[System.Collections.Generic.IEnumerable
我已经验证连接字符串正常,并且可以毫无问题地连接到测试数据库,但我对异常感到困惑。
接下来我可以尝试什么?
这就是我解决问题的方法,只需将函数放入 Use() 中即可:
Public Shared Sub Init()
Dim connStr = "Data Source=xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx"
HangfireAspNet.Use(
Iterator Function()
GlobalConfiguration.Configuration.SetDataCompatibilityLevel(CompatibilityLevel.Version_170).UseSimpleAssemblyNameTypeSerializer().UseRecommendedSerializerSettings().UseSqlServerStorage(connStr, New SqlServerStorageOptions With {
.CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
.SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
.QueuePollInterval = TimeSpan.Zero,
.UseRecommendedIsolationLevel = True,
.DisableGlobalLocks = True
})
Yield New BackgroundJobServer()
End Function
)
End Sub
在 VB 中,您必须在过程调用中使用 AddressOf,即:
HangfireAspNet.Use(AddressOf GetHangfireServers)