可以使 WCF 服务在本地运行(项目参考)或作为基于 web.config 上的某些键的服务。我做了下面的例子,但我没有测试它,但我之前做过完全相似的事情
在 web 配置中添加密钥说 serviceMode="local/service"
然后说你有wcf服务接口
[ServiceContract]
public class ICalculator
{
[OperationContract]
int Add(int x, int y);
}
执行
public class Calculator
{
public int Add(int x, y)
{
return x+y;
}
}
///现在在您的网络应用程序中
你将会有
public LocalProxy:ICalculator //this will use direct instance of the Calculator Service
{
private ICalculator _calculator
public LocalProxy(ICalculator calculator)
{
_calculator =calculator;
}
public int Add(int x, int y)
{
return _calculator.Add(x,y);
}
}
public class RemoteProxy:ICalculator ///This will be real wcf proxy
{
public int Add (int x,int y)
{
var endpointAddress = new EndpointAddress(EndpointUrl);
ChannelFactory<ICalculator> factory = null;
ICalculator calculator ;
try
{
// Just picking a simple binding here to focus on other aspects
Binding binding = new BasicHttpBinding();
factory = new ChannelFactory<ICalculator>(binding);
calculator= factory.CreateChannel(endpointAddress);
if (calculator== null)
{
throw new CommunicationException(
String.Format("Unable to connect to service at {0}", endpointUrl));
}
int sum= calculator.Add(x,y);
((IClientChannel)calculator).Close();
calculator = null;
factory.Close();
factory = null;
return sum;
}
finally
{
if (calculator!= null) ((IClientChannel)calculator).Close();
if (factory != null) factory.Abort();
}
}
}
现在你如何使用它
ICalculator _calculatorProxy;
//get the web config key here, you may use strategy pattern to select between the two proxies
if(key=="local)
{
_calculator= new LocalProxy(new Calculator)
}
else
{
_calculator= new RemoteProxy();
}
//then
_calculator.Add(3,5);
注意:在单独的程序集中定义您的接口和数据协定,以便您可以与需要 wcf 作为服务运行的 Web 应用程序共享它。