制作一个小型WCF
测试程序,该程序基于具有客户和每个客户的商店,具有特殊点的余额。现在我想专注于拥有固定数量的客户,比如说3.问题是我无法解决我在哪里创建这些客户以及如何从服务的功能中访问它们。我想在服务的main()
内创建一组客户,以便稍后客户可以使用它们,但这是一个好主意吗?非常新鲜WCF
,无法找到任何可以展示如何实现此类内容的示例。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.ServiceModel.Description;
namespace StoreService
{
public class Program
{
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://localhost:6112/StoreService");
ServiceHost host = new ServiceHost(typeof(Store), baseAddress);
try
{
host.AddServiceEndpoint(typeof(IStore), new WSHttpBinding(), "Store");
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
host.Description.Behaviors.Add(smb);
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate the service.");
Console.WriteLine();
Console.ReadLine();
host.Close();
}
catch (CommunicationException ce)
{
Console.WriteLine("An exception occured: {0}", ce.Message);
host.Abort();
}
}
}
[ServiceContract(Namespace="http://StoreService")]
public interface IStore
{
[OperationContract]
void AddPoints(string accNum, double points);
[OperationContract]
void SubtractPoints(string accNum, double points);
[OperationContract]
int CustomerPoints(string accNum);
}
[DataContract]
public class Customer
{
private string accountNumber;
private string name;
private double points;
[DataMember]
public int AccountNumber
{
get { return accountNumber; }
set { accountNumber = value; }
}
[DataMember]
public string Name
{
get { return name; }
set { name = value; }
}
[DataMember]
public int Points
{
get { return points; }
set { points = value; }
}
}
public class Store : IStore
{
public void AddPoints(string accNum, double points)
{
//Add points logic
}
public void SubtractPoints(string accNum, double points);
{
//Substract points logic
}
public int CustomerPoints(string accNum)
{
//Show points
}
}
}
答案 0 :(得分:2)
您需要一个服务接口和服务公开的每种方法的代码。
这是我的头脑,未经测试,微软的例子会告诉你Bryan发布的这些东西
例如,添加2个新类:
// First the Interface, things in here decorated with the Operation contract gets exposed, things with serializable are available to the client
namespace MyService
{
[ServiceContract]
public interface ICustomer
{
[OperationContract]
int GetBalance(Guid CustomerId);
}
[Serializable]
public class Customer
{
public Guid Id;
public int Balance;
}
}
// 2nd class file is the code mapping to the interface
namespace MyService
{
private List<Customer> Customers = new List<Customer>();
public class MyService : ICustomer
{
public int GetBalance(Guid CustomerId)
{
foreach(Customer c in Customers)
{
if(c.Id == CustomerId)
{
return c.Balance;
}
}
}
}
}
答案 1 :(得分:0)