请原谅我这个可能很愚蠢的问题,总体上我还是不太熟悉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
下的两行都用红色下划线。我想念什么?
答案 0 :(得分:0)
Hangfire
(另请参见Hangfire Installation Guide)。对于Visual Studio Professional 2017,您可以执行以下操作:
Manage NuGet Packages
。nuget.org
,然后使用左上方的搜索栏搜索Hangfire
。Hangfire
,然后点击安装。出现弹出窗口时,您可能需要单击接受。using System.Configuration;
的标题中添加Global.asax.cs
。以下所有步骤将在该文件中进行。connections.config
获取数据库上下文定义:string connString = ConfigurationManager.ConnectionStrings["ConStringName"].ToString();
System.Web.Http
,则必须用GlobalConfiguration.xxx
替换System.Web.Http.GlobalConfiguration.xxx
的所有外观。这是避免冲突的必要步骤,因为两个软件包都具有(不同的)GlobalConfiguration
属性。connString
:我们将代替GlobalConfiguration.Configuration.UseSqlServerStorage("HardcodedContextString");
必须写Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage(connString);
PS:从https://stackoverflow.com/a/6134384/1236044我学习了如何从配置文件中获取连接字符串-感谢@ jbl指出这一点。 JBL还给了我有关名称空间冲突的提示。