我正在创建 asp.net 网络服务。我有一个类,当我尝试初始化该类的对象时,它的静态构造函数没有被调用。我无法理解这种行为。在静态构造函数中,我正在从 web.config 文件中读取值。
部分代码如下:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
AppController extractor;
public Service()
{
try
{
extractor = new AppController();
}
catch(Exception ex)
{
// I am not getting exception at this point.
}
}
}
public class AppController
{
static string converterBatchFilePath = null;
static string personalProfileOutputFolderPath = null;
static AppController()
{
// reading some settings from web.config file
try
{
converterBatchFilePath = ConfigurationManager.AppSettings["WordToTextConverterBatFilePath"];
}
catch(Exception ex)
{ // }
}
public AppController()
{
// do some initialization
}
}
在调试 Web 服务时,我注意到只有实例构造函数被调用并且控制永远不会转到静态构造函数。
有人知道为什么会这样吗?
我正在使用 VS 2008 Express 版和 C#。
EDIT
实际上这个 AppController 是基于控制台的项目。我已经将该项目添加为 Web 服务项目中的引用,然后使用它。如果我从命令行使用 AppController,它工作正常,但它不能在 Web 服务项目内部工作。
最佳答案
我的猜测是它在您预期被调用之前就被调用了。如果您已经调试了您的站点但没有回收 AppPool,则很可能静态构造函数已经运行。 类似地,任何访问任何静态成员的东西也将调用静态构造函数(如果尚未调用的话)。
关于c# - 为什么这个静态构造函数没有被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7400438/