如何使用ASP.NET配置hangfire以从配置文件获取连接字符串?

时间:2020-01-14 14:46:26

标签: c# asp.net dbcontext hangfire

请原谅我这个可能很愚蠢的问题,总体上我还是不太熟悉ASP.NET架构。

我继承了一个大项目,我打算setup hangfire.io。我知道我必须以某种方式初始化数据库上下文,但是我不想按照hangfire-docu的建议对其进行硬编码。

我的API\Global.asax.cs当前看起来如下,有趣的东西开始于// Hangfire stuff之后:

using System.Web.Http;
using System.Web.Http.ExceptionHandling;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Hangfire;

namespace API
{
   public class WebApiApplication : System.Web.HttpApplication
   {
       protected void Application_Start()
       {
          log4net.Config.XmlConfigurator.Configure();
          GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new GlobalExceptionLogger());
          GlobalConfiguration.Configuration.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
          MvcHandler.DisableMvcResponseHeader = true;
          AreaRegistration.RegisterAllAreas();
          GlobalConfiguration.Configure(WebApiConfig.Register);
          FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
          RouteConfig.RegisterRoutes(RouteTable.Routes);
          MapperConfig.RegisterMapper();

          // Hangfire stuff  
          GlobalConfiguration.Configuration.UseSqlServerStorage("HardcodedContextString");
          RecurringJob.AddOrUpdate("some-id", () => Console.WriteLine("My hangfire test."), "*/2 * * * 1-5"); 
       }
   }
}

我的数据库上下文myContext似乎在API\connections.config内部定义,其中包含以下几行:

<?xml version="1.0"?>
  <connectionStrings>
    <add name="myContext" connectionString="Data Source=localhost\sqlexpress;Initial Catalog=myContext;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
  </connectionStrings>

我应该用什么代替HardcodedContextString来使ASP.NET从相应的配置文件中读取连接字符串?

PS:有趣的是,// Hangfire stuff下的两行都用红色下划线。我想念什么?

参考文献

1 个答案:

答案 0 :(得分:0)

  1. 确保已实际安装Hangfire(另请参见Hangfire Installation Guide)。对于Visual Studio Professional 2017,您可以执行以下操作:
    1. 右键单击您的项目,然后单击Manage NuGet Packages
    2. 选择数据包来源:nuget.org ,然后使用左上方的搜索栏搜索Hangfire
    3. 选择Hangfire,然后点击安装。出现弹出窗口时,您可能需要单击接受
  2. using System.Configuration;的标题中添加Global.asax.cs。以下所有步骤将在该文件中进行。
  3. 定义一个变量,该变量从connections.config获取数据库上下文定义:
string connString = ConfigurationManager.ConnectionStrings["ConStringName"].ToString();
  1. 如果像我一样使用System.Web.Http,则必须用GlobalConfiguration.xxx替换System.Web.Http.GlobalConfiguration.xxx的所有外观。这是避免冲突的必要步骤,因为两个软件包都具有(不同的)GlobalConfiguration属性。
  2. 我们还必须为Hangfire指定完整的名称空间。我们现在还将使用connString:我们将代替GlobalConfiguration.Configuration.UseSqlServerStorage("HardcodedContextString"); 必须写
Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage(connString);
  1. 所有内容现在都应该正确编译。

PS:https://stackoverflow.com/a/6134384/1236044我学习了如何从配置文件中获取连接字符串-感谢@ jbl指出这一点。 JBL还给了我有关名称空间冲突的提示。

相关问题