[英]WCF Service - instantiating a class
I'm creating a WCF service (.NET 4.0/c#)... I added a new class to the project and I'm trying to instantiate it like so: 我正在创建WCF服务(.NET 4.0 / c#)...我在项目中添加了一个新类,并且试图像这样实例化它:
MyNewClass inst = new MyNewClass();
... but I'm getting the famous, "Object reference not set an instance of an object" message at that line. ...但是我在那一行得到了著名的“对象引用未设置对象实例”消息。
What could I be doing wrong? 我可能做错了什么?
EDIT: 编辑:
Here's the class: 这是课程:
using System;
using bla, bla, blah...
public class MyNewClass
{
private string cnn1 = ConfigurationManager.ConnectionStrings["connection_string_1"].ConnectionString;
private string cnn2 = ConfigurationManager.ConnectionStrings["connection_string_2"].ConnectionString;
public string Conn(string s)
{
string cnn = string.Empty;
switch (s)
{
case "Server1":
cnn = cnn1;
break;
case "Server2":
cnn = cnn2;
break;
}
return cnn;
}
}
You should pass in a configuration object rather than calling the ConfigurationManager. 您应该传递配置对象,而不是调用ConfigurationManager。 That would allow you to use the class indenpendent of an appconfig / webconfig.
那将允许您使用appconfig / webconfig的类无关项。
For instance, perhaps 例如,也许
public MyClass(string conn1, string conn2)
{...}
Or at least check for null before accessing a property, 或者至少在访问属性之前检查是否为空,
For instance, change this to be in the contructor 例如,将其更改为构造器
private string cnn1;
public MyClass()
{
if (ConfigurationManager.ConnectionStrings["connection_string_1"] != null)
cnn1 = ConfigurationManager.ConnectionStrings["connection_string_1"].ConnectionString;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.