问题描述
我的应用中有代码:
[ServiceContract(Namespace = "")]
public class Service1
{
[OperationContract]
public object SomeMethod1(){}
}
[ServiceContract(Namespace = "")]
public class Service2
{
[OperationContract]
public object SomeMethod2()
{
var result = new Service1().someMethod1();
}
}
我必须使用某种代理来调用 service1 方法还是正确的方法?
解决方法
我们不能这样做。在WCF中,每个ServiceContract对应一个端点,调用不同的端点需要不同的代理,因为这些端点的地址信息是不一样的。
这是一个演示:
[ServiceContract]
public interface ICalculator
{
[OperationContract]
double Add(double n1,double n2);
}
[ServiceContract]
public interface ICalculator2
{
[OperationContract]
double Subtract(double n1,double n2);
}
public class CalculatorService : ICalculator,ICalculator2
{
public double Add(double n1,double n2)
{
double result = n1 + n2;
Console.WriteLine("Received Add({0},{1})",n1,n2);
Console.WriteLine("Return: {0}",result);
return result;
}
public double Subtract(double n1,double n2)
{
double result = n1 - n2;
Console.WriteLine("Received Subtract({0},result);
return result;
}
}
class Program
{
static void Main(string[] args)
{
// Step 1: Create a URI to serve as the base address.
Uri baseAddress = new Uri("http://localhost:8000/GettingStarted/");
// Step 2: Create a ServiceHost instance.
ServiceHost selfHost = new ServiceHost(typeof(CalculatorService),baseAddress);
try
{
// Step 3: Add a service endpoint.
selfHost.AddServiceEndpoint(typeof(ICalculator),new BasicHttpBinding(),"CalculatorService");
selfHost.AddServiceEndpoint(typeof(ICalculator2),"CalculatorService2");
// Step 4: Enable metadata exchange.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smb);
// Step 5: Start the service.
selfHost.Open();
Console.WriteLine("The service is ready.");
// Close the ServiceHost to stop the service.
Console.WriteLine("Press <Enter> to terminate the service.");
Console.WriteLine();
Console.ReadLine();
selfHost.Close();
}
catch (CommunicationException ce)
{
Console.WriteLine("An exception occurred: {0}",ce.Message);
selfHost.Abort();
}
}
}
上述服务中有两个ServiceContract,一个是ICalculator,另一个是ICalculator2。它们的端点地址不同。
当我们添加服务引用时,会生成两个代理类,并且两个代理类的端点地址不同:
所以我们不能使用同一个代理类来调用不同的ServiceContracts。