wcf服务初始化

时间:2013-04-16 10:39:12

标签: wcf parameters constructor

我有一个简单包装组件方法的服务。 我以编程方式创建服务,我需要使用组件初始化它(作为构造函数中的参数传入,具有setter方法或任何方式)。我的服务是在Windows服务中自托管的。我读到了有关IInstanceProvider和ServiceHost方法的内容,但我认为它可能更多地用于DI容器,而我需要做的事情应该更加简单。 任何建议将不胜感激。这是我的示例代码:

  1. 以编程方式创建服务:

    _plcServiceHost = new ServiceHost(typeof(PLCService));
    
    
        foreach (var plc in PLCRepository.GetAllLocal())
        {
            var baseAddress = plc.LocalEndpointName;
    
            var binding = new NetTcpBinding();
    
            _plcServiceHost.AddServiceEndpoint(typeof(IPLCService), binding, baseAddress);
    
    
            AddMetadataExchange(_plcServiceHost, baseAddress);
        }
    
    _plcServiceHost.Open();
    
  2. 这就是我想要服务的方式(2a或2b)。 2A。带有setter的PLC服务:

        [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
        public class PLCService : IPLCService
        {
            #region fields
            public static volatile object HardwareLock = new object();
            private IPLCImpl _plc;
            private Semaphore _unsubscribeSem;
            private bool _isSubscribed;
    
            #endregion
    
            public void SetPLC(IPLCImpl plc)
            {
                if (plc == null) throw new ArgumentNullException("plc");
    
                _plc = plc;
    
                _plc.Connect();
            }
    

    2B。在构造函数上初始化的PLC服务:

        [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
        public class PLCService : IPLCService
        {
            #region fields
            public static volatile object HardwareLock = new object();
            private readonly IPLCImpl _plc;
            private Semaphore _unsubscribeSem;
            private bool _isSubscribed;
    
            #endregion
    
            public PLCService(IPLCImpl plc)
            {
                if (plc == null) throw new ArgumentNullException("plc");
    
                _plc = plc;
    
                _plc.Connect();
            }
    

1 个答案:

答案 0 :(得分:0)

您可以使用提到的DI,如Unity,Castle等,从服务外部启动实施。

通过这种方式,您可以在PLCService构造函数中使用它。

相关问题