读书人

怎么给WCF添加自定义构造函数

发布时间: 2012-03-28 15:40:03 作者: rapoo

如何给WCF添加自定义构造函数
默认添加一个WCF服务(如下),想通过添加自定义构造函数传入参数,初始化值,但添加后无法编译通过,不知道如何处理?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WcfServiceLibrary1
{
// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IService1”。
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);

[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);

// TODO: 在此添加您的服务操作
}

// 使用下面示例中说明的数据协定将复合类型添加到服务操作
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";

[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}

[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
}



using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WcfServiceLibrary1
{
// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的类名“Service1”。
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}

public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
}


[解决办法]
只使用无参数构造函数 初始化时用你的默认值 如果有必要用户自定义这2个值 可以写个ini(string a,bool b )

让用户程序调用这个函数完成自定义这2个值的啊

[解决办法]
[DataMember]
public Int32 City { get; set; }
[OnDeserialized]
public void SetDeafultValue(StreamingContext context)
{
this.City= 123;
}
[解决办法]
什么叫初始化参数?你给的代码里根本没看到你有初始化参数的操作。参数只能给默认值,而且也只有在Visual Studio 2010里面才支持带默认值参数的函数。
[解决办法]
在WCF的服务里面,不支持带参数的构造函数。另外当你给了一个带参数的构造函数,就不会自动添加一个无参的构造函数了,而无参构造函数是必须的,因此最终编译就报错。

其实要达到你的目的,非常简单,你只要将需要设置的变量定义为全局的静态变量,在外部设置好,这样服务类内部就可以访问了。

读书人网 >C#

热点推荐