[英]wcf duplex service lose coupling with client
我在一個問題上停留了兩個星期。
假設我們有一個Duplex WCF服務和一個調用該服務的客戶端應用程序。
該應用程序具有由服務組成的類MyCallBackClass。 我想要實現的是在MyCallBackClass客戶端應用程序的構造函數中傳遞實例化的服務(丟失耦合)。 因此,它看起來像是一種方法的服務和一種方法的回調:
雙工服務合同:
[ServiceContract(SessionMode=SessionMode.Required,CallbackContract=typeof(ICallback))]
public interface IService{
[OperationContract(IsOneWay = true)]
void GetDataFromService();
}
雙重回調:
public interface ICallback{
[OperationContract(IsOneWay = true)]
void ReceiveMessage(string message);
}
DUPLEX SERVICE實施
public class Service : IService{
//... here a reference to the Callback endpoint
void GetDataFromService(){
callBackEndPoint.ReceiveMessage("Service was called.");
}
}
造成回調的我的班級:
public class MyCallBackClass : ICallback, Widnows.Form
{
IService service;
public MyCallBackClass (){
InstanceContext instanceContext = new InstanceContext(this);
this.service = new ServiceClient(instanceContext);
}
public ReceiveMessage(string message){
this.textBoxMessage.Text = message;
//here I want to stress that I would like my CallBack object to be a Form or WPF Form
//so that I can react on callbacks by modyfing the Controls like TextBox, ListBox directly
}
}
現在在應用程序中,我被迫在實現回調接口的對象的構造函數中實例化服務,假設它是Form或WPF Form(如下所示):
public void Main(string[] args){
MyCallBackClass myWindow = new MyCallBackClass();
myWindow.GetDataFromService();
}
我想擁有的是通過回調處理程序的構造函數中的服務通過,如下所示:
public void Main(string[] args){
Iservice service = new ServiceClient();// but what about the InstanceContext that is the MyCallBackClass object...???
MyCallBackClass myWindow = new MyCallBackClass(service);
myWindow.GetDataFromService();
}
當然,該類的MyCallBackClass構造函數將更改為:
public class MyCallBackClass : ICallback, Widnows.Form
{
IService service;
public MyCallBackClass (IService _service){
InstanceContext instanceContext = new InstanceContext(this);
this.service = _service;
...
}
這樣我就可以向客戶端類注入實現IService接口的任何類型的服務,並且可以通過模擬Service來輕松測試客戶端類。 不幸的是,我遇到了依賴循環。 InstanceContext依賴MyCallBackClass依賴IService依賴InstanceContext ...
您能否嘗試理解並嘗試指導我解決該問題的任何方向?
你可以試試看。 win.service.Value是首次使用Service的時間(實例將引用原始的委托)。 也可以使用Windows上的SetService方法來完成此操作,區別在於創建Windows實例時可能會忘記調用它。 所有必需項都必須位於Windows的構造函數中,即Contract,Function和Lazy load使您的依賴關系生效:)
您絕對應該重構代碼,嘗試閱讀SOLID原則。
public class Service
{
private int number;
private Window win;
public Service(int num, Window win)
{
number = num;
this.win = win;
}
}
public class Window
{
public Lazy<Service> service;
public Window(Func<Service> getService)
{
service = new Lazy<Service>(getService);
}
}
static void Main(string[] args)
{
Service s = null;
var win = new Window(() => s);
s = new Service(1, win);
Service winS = win.service.Value;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.