日期:2014-05-18  浏览次数:20711 次

如何给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的服务里面,不支持带参数的构造函数。另外当你给了一个带参数的构造函数,就不会自动添加一个无参的构造函数了,而无参构造函数是必须的,因此最终编译就报错。

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