gpt4 book ai didi

c# - 自承载 WCF 服务 : How to access the object(s) implementing the service contract from the hosting application?

转载 作者:太空狗 更新时间:2023-10-29 20:02:05 26 4
gpt4 key购买 nike

我在 WPF 客户端中自行托管 WCF 服务。我想在用户界面中显示服务接收到的数据。每次收到一些数据时,用户界面都应该更新。

“App.xaml.cs”中的代码看起来像

    private ServiceHost _host = new ServiceHost(typeof(MyService));

private void Application_Startup(object sender, StartupEventArgs e)
{
_host.Open();
}

private void Application_Exit(object sender, ExitEventArgs e)
{
_host.Close();
}

如何从托管 WPF 应用程序获取实现服务契约的对象实例?


谢谢大家的回答。

我没有看到的是,ServiceHost 的构造函数允许传递服务的实例,而不是它的类型

所以我现在做的是:

  • 在服务实现中使用 ObservableCollection
  • 将服务配置为单例(参见 theburningmonk 的评论)
  • 绑定(bind)到我的 WPF 应用程序中的 ObservableCollection
  • 使用数据绑定(bind)属性获取服务实例 DataContext
  • 传递给ServiceHost的构造函数

结果:单例 WCF 服务中的每个更新都反射(reflect)在 UI 中。

快乐!

最佳答案

正如 marc_s 所说,您正在创建一个 PerCall/PerSession WCF 服务,并且在每个 session 的每个请求/第一个请求上创建一个新实例。

您可以围绕它构建一些管道,以便实例可以在收到新请求时通知服务主机,但这不是一个简单的练习,如果您决定这样做,您需要注意内存泄漏的可能性继续使用事件来做到这一点——如果不实现弱事件模式,您的 WCF 服务实例可能会被挂起,因为事件处理程序仍然持有对它们的引用,除非您记得在处理 WCF 服务实例时通知主机取消订阅。

相反,这里有两个想法可能会让您更轻松地实现目标:

使用 InstanceContextMode如果您的服务可以成为单例,在这种情况下,您将创建一个新实例来实现您的服务契约(Contract)并托管它:

// instance will be your WCF service instance
private ServiceHost _host = new ServiceHost(instance);

这样您就可以访问将检索客户端请求的实例。

或者,您可以将所有托管实例设为虚拟“fascades”,它们共享一个实际处理请求的静态类:

[ServiceContract]
interface IMyService { ... }

interface IMyServiceFascade : IMyService { ... }

// dummy fascade
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall]
public class MyServiceFascade : IMyServiceFascade
{
private static IMyService _serviceInstance = new MyService();

public static IMyService ServiceInstance { get { return _serviceInstance; } }

public int MyMethod()
{
return _serviceInstance.MyMethod();
}
...
}

// the logic class that does the work
public class MyService : IMyService { ... }

// then host the fascade
var host = new ServiceHost(typeof(MyServiceFascade));

// but you can still access the actual service class
var serviceInstance = MyServiceFascade.ServiceInstance;

我想说的是,如果可能的话,您应该采用第一种方法,这样生活会更轻松一些!

关于c# - 自承载 WCF 服务 : How to access the object(s) implementing the service contract from the hosting application?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3469044/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com