[英]WCF services consuming
我有兩個項目,一個是一組WCF服務(我們稱為P1),另一個是標准Web應用程序(P2)。
首先,我們將P2中的P1服務用作SOAP服務,並且一切正常。 后來我們注意到,在我們所有的項目部署中,我們都將P1和P2托管在同一服務器上。 因此,我們想到了為什么要這樣保持它的意思-意思是:為什么每次在同一服務器上運行的每個方法,我們都應該每次對請求/響應進行序列化/反序列化。 因此,我們決定使用P1作為P2中的標准項目庫參考。
我們必須進行大量修改,因為代理類名稱發生了變化,並且每次調用后都必須刪除客戶端的“ close”方法。 現在,我們有了一個新的部署,它將要求P1可以與P2放在不同的服務器上,並且可以更改,並且我們必須再次使用P1作為WCF服務-這意味着在P2上要進行大量更改,並通過序列化來結束所有其他部署的開銷!
問題是,是否有任何方法可以動態引用P1,所以無論部署在1台或2台服務器上,都不需要編碼?
可以使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;
}
}
///現在在您的Web應用程序中
您將擁有
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應用程序共享它們。
P2中所有使用P1服務的組件都應僅使用服務接口(即IMyService
, ISomeOtherService
)。 他們不必在乎它是本地實例還是代理,也不應該關閉連接。
實現這一點的最簡單(恕我直言)是通過像溫莎城堡(Castle Windsor)這樣的IoC使用依賴注入(這是我所不熟悉的唯一一個,但還有其他幾個)。 容器將負責提供服務接口的實例。 您可以提供不同的實現,並在運行時使用適當的實現(WCF服務或本地實例)配置容器。 一旦不再需要這些服務組件,容器還將負責處理這些服務組件(即,在WCF代理上調用Close()
,對其他組件則不執行任何操作)。
這是一個很大的話題,所以我建議您在互聯網上搜索一些關鍵字-那里有很多資料。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.