TypeInitializationException:'vService.CheckService'的类型初始值设定项引发了异常

时间:2012-04-02 11:15:59

标签: c# wcf faultexception

我在调用WCF服务时收到一个FaultException,如下所示:

2012-04-02 16:26:00.3593|Error|System.ServiceModel.FaultException`1[System.ServiceModel.ExceptionDetail]: The type initializer for 'vService.CheckService' threw an exception. (Fault Detail is equal to An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
System.TypeInitializationException: The type initializer for 'vService.CheckService' threw an exception. ----> System.NullReferenceException: Object reference not set to an instance of an object.
   at vService.CheckService..cctor() in d:\working\code\VioletServer\vService\CheckService.cs:line 14
   --- End of inner ExceptionDetail stack trace ---
   at vService.CheckService..ctor()
   at CreatevService.CheckService()
   at System.ServiceModel.Dispatcher.InstanceProvider.GetInstance(InstanceContext instanceContext, Message message)
   at System.ServiceModel.Dispatcher.InstanceBehavior.GetInstance(InstanceContext instanceContext, Message request)
   at System.ServiceModel.InstanceContext.GetServiceInstance(Message message)
   at System.ServiceModel.Dispatcher.InstanceBehavior.EnsureServiceInstance(MessageRpc& rpc)
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc)
  ...).

CheckService.cs的第14行是

private static string connStr = ConfigurationManager.ConnectionStrings["violetdb"].ConnectionString;

在此背景下,异常是什么意思,我该如何解决?


//CheckService.cs
public class CheckService : ICheckService
{
    private static string connStr = ConfigurationManager.ConnectionStrings["violetdb"].ConnectionString;
    MessageRepository _repo = new MessageRepository(connStr);

    public CheckService(){}

    public CheckService(MessageRepository repo)
    {
        _repo = repo;
    }

    public void SendMessage(string sender, string recipient, string messagetext)
    {
        _repo.DeliverMessage(sender,recipient,messagetext);
    }
}

1 个答案:

答案 0 :(得分:4)

您的WCF服务很可能在其应用程序配置文件中没有名为“violetdb”的连接字符串。

在这种情况下会引发TypeInitializerException,因为您有一个static字段,该字段在类型构造之前被初始化,并且ConnectionStrings["violetdb"]调用正在返回null ,它正在抛出一个NullReferenceException

底线,检查配置文件的<connectionStrings>部分,确保连接字符串存在。