语境:
我需要开发一个监视服务器来监视我们的一些应用程序(这些应用程序在c#中).所以我决定使用WCF开发系统,这似乎适合我的需求.
这些应用程序在启动时必须将自己注册到监视服务器.之后,监视服务器可以调用这些应用程序的Start或Stop方法.
一切都在同一台机器上完全执行,无需远程执行任何操作.
所以我开发了一个很好的原型,一切正常.每个应用程序将自己注册到监视服务器.
题:
ApplicationRegistrationService(请参阅下面的代码)是监视服务的实现,由于ServiceBehavior属性,它是一个单例实例.
这里是我的问题:我想访问每个示例的ApplicationRegistrationService内容,来自我的服务器的连接应用程序的数量(示例中为ConsoleMonitoringServer).但是,我不知道如何实现这一目标.
我是否需要像我在客户端(ConsoleClient)中那样在服务器中创建一个服务通道,或者它是否有更好的方法来实现这一目标?
码:
出于此问题的目的,代码非常简化:
- //The callback contract interface
- public interface IApplicationAction
- {
- [OperationContract(IsOneWay = true)]
- void Stop();
- [OperationContract(IsOneWay = true)]
- void Start();
- }
- [ServiceContract(SessionMode = SessionMode.required,CallbackContract = typeof(IApplicationAction))]
- public interface IApplicationRegistration
- {
- [OperationContract]
- void Register(Guid guid,string name);
- [OperationContract]
- void Unregister(Guid guid);
- }
- [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,ConcurrencyMode = ConcurrencyMode.Multiple)]
- public class ApplicationRegistrationService : IApplicationRegistration
- {
- //IApplicationRegistration Implementation
- }
- public class ApplicationAction : IApplicationAction
- {
- //IApplicationAction Implementation
- }
此示例的控制台应用程序
- class ConsoleClient
- {
- static void Main(string[] args)
- {
- ApplicationAction actions = new ApplicationAction();
- DuplexChannelFactory<IApplicationRegistration> appRegPipeFactory =
- new DuplexChannelFactory<IApplicationRegistration>(actions,new NetNamedPipeBinding(),new EndpointAddress("net.pipe://localhost/AppReg"));
- IApplicationRegistration proxy = appRegPipeFactory.CreateChannel();
- proxy.Register(Guid.Empty,"ThisClientName");
- //Do stuffs
- }
- }
此示例的控制台服务器
- class ConsoleMonitoringServer
- {
- static void Main(string[] args)
- {
- using (ServiceHost host = new ServiceHost(typeof(ApplicationRegistrationService),new Uri[]{ new Uri("net.pipe://localhost")}))
- {
- host.AddServiceEndpoint(typeof(IApplicationRegistration),"AppReg");
- host.Open();
- //Wait until some write something in the console
- Console.ReadLine();
- host.Close();
- }
- }
- }
解决方法
最后,我找到答案,这很容易.我只需要创建服务实例并将引用传递给ServiceHost的构造函数.
所以我需要替换以下代码:
- using (ServiceHost host = new ServiceHost(typeof(ApplicationRegistrationService),new Uri[]{ new Uri("net.pipe://localhost")}))
通过:
- ApplicationRegistrationService myService = new ApplicationRegistrationService();
- using (ServiceHost host = new ServiceHost(myService,new Uri[]{ new Uri("net.pipe://localhost")}))