我已经坚持了两个星期的问题。
假设我们有一个Duplex WCF服务和一个调用该服务的客户端应用程序。
该应用程序有一个由服务组成的类MyCallBackClass。我想要实现的是在MyCallBackClass客户端应用程序的构造函数中传递实例化的服务(丢失耦合)。所以它看起来像一个方法的服务和一个方法的回调:
DUPLEX服务合同:
[ServiceContract(SessionMode=SessionMode.Required,CallbackContract=typeof(ICallback))]
public interface IService{
[OperationContract(IsOneWay = true)]
void GetDataFromService();
}
DUPLEX CALLBACK:
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接口的服务注入到客户端类中,并且通过模拟服务可以很容易地测试客户端类。不幸的是,我遇到了依赖性循环。 InstanceContext依赖于依赖于InstanceContext的IService的MyCallBackClass ......
您能否尝试理解并尝试指导我解决此问题的任何方向?
答案 0 :(得分:0)
你可以试试这个。 win.service.Value是Service首次使用时将被实例化的时间(使用委托引用原始版本)。这也可以在Windows上使用方法SetService完成,不同之处在于有人可能忘记在创建Windows实例时调用它。所有必需项必须在Windows的构造函数中,即Contract,Function以及Lazy load使您的Dependency活动:)
您绝对应该重构代码,尝试阅读有关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;
}