[英]How to call WCF service from another service method?
我的應用程序中有代碼:
[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對應一個endpoint,調用不同的endpoint需要不同的代理,因為這些endpoint的地址信息不一樣。
這是一個演示:
[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},{1})", n1, n2);
Console.WriteLine("Return: {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), new BasicHttpBinding(), "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。 它們的端點地址不相同。
當我們添加服務引用時,會生成兩個代理類,兩個代理類的端點地址不同:
所以我們不能使用同一個代理class來調用不同的ServiceContracts。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.