c# – WCF:从服务器访问服务实例

前端之家收集整理的这篇文章主要介绍了c# – WCF:从服务器访问服务实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
语境:

我需要开发一个监视服务器来监视我们的一些应用程序(这些应用程序在c#中).所以我决定使用WCF开发系统,这似乎适合我的需求.

这些应用程序在启动时必须将自己注册到监视服务器.之后,监视服务器可以调用这些应用程序的Start或Stop方法.

一切都在同一台机器上完全执行,无需远程执行任何操作.

所以我开发了一个很好的原型,一切正常.每个应用程序将自己注册到监视服务器.

题:

ApplicationRegistrationService(请参阅下面的代码)是监视服务的实现,由于ServiceBehavior属性,它是一个单例实例.

这里是我的问题:我想访问每个示例的ApplicationRegistrationService内容,来自我的服务器的连接应用程序的数量(示例中为ConsoleMonitoringServer).但是,我不知道如何实现这一目标.

我是否需要像我在客户端(ConsoleClient)中那样在服务器中创建一个服务通道,或者它是否有更好的方法来实现这一目标?

码:

出于此问题的目的,代码非常简化:

  1. //The callback contract interface
  2. public interface IApplicationAction
  3. {
  4. [OperationContract(IsOneWay = true)]
  5. void Stop();
  6.  
  7. [OperationContract(IsOneWay = true)]
  8. void Start();
  9. }
  10.  
  11. [ServiceContract(SessionMode = SessionMode.required,CallbackContract = typeof(IApplicationAction))]
  12. public interface IApplicationRegistration
  13. {
  14. [OperationContract]
  15. void Register(Guid guid,string name);
  16.  
  17. [OperationContract]
  18. void Unregister(Guid guid);
  19. }
  20.  
  21. [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,ConcurrencyMode = ConcurrencyMode.Multiple)]
  22. public class ApplicationRegistrationService : IApplicationRegistration
  23. {
  24. //IApplicationRegistration Implementation
  25. }
  26.  
  27. public class ApplicationAction : IApplicationAction
  28. {
  29. //IApplicationAction Implementation
  30. }

此示例的控制台应用程序

  1. class ConsoleClient
  2. {
  3. static void Main(string[] args)
  4. {
  5. ApplicationAction actions = new ApplicationAction();
  6.  
  7. DuplexChannelFactory<IApplicationRegistration> appRegPipeFactory =
  8. new DuplexChannelFactory<IApplicationRegistration>(actions,new NetNamedPipeBinding(),new EndpointAddress("net.pipe://localhost/AppReg"));
  9.  
  10. IApplicationRegistration proxy = appRegPipeFactory.CreateChannel();
  11. proxy.Register(Guid.Empty,"ThisClientName");
  12.  
  13. //Do stuffs
  14. }
  15. }

此示例的控制台服务器

  1. class ConsoleMonitoringServer
  2. {
  3. static void Main(string[] args)
  4. {
  5. using (ServiceHost host = new ServiceHost(typeof(ApplicationRegistrationService),new Uri[]{ new Uri("net.pipe://localhost")}))
  6. {
  7. host.AddServiceEndpoint(typeof(IApplicationRegistration),"AppReg");
  8.  
  9. host.Open();
  10.  
  11. //Wait until some write something in the console
  12. Console.ReadLine();
  13.  
  14. host.Close();
  15. }
  16. }
  17. }

解决方法

最后,我找到答案,这很容易.我只需要创建服务实例并将引用传递给ServiceHost的构造函数.

所以我需要替换以下代码

  1. using (ServiceHost host = new ServiceHost(typeof(ApplicationRegistrationService),new Uri[]{ new Uri("net.pipe://localhost")}))

通过:

  1. ApplicationRegistrationService myService = new ApplicationRegistrationService();
  2.  
  3. using (ServiceHost host = new ServiceHost(myService,new Uri[]{ new Uri("net.pipe://localhost")}))

猜你在找的C#相关文章