我有一个简单地包装组件方法的服务。我以编程方式创建服务,并且需要使用组件对其进行初始化(在构造函数中作为参数传入,具有 setter 方法或任何方式)。我的服务在 Windows 服务中自托管。我阅读了有关 IInstanceProvider 和 ServiceHost 方法的信息,但是我认为这可能更多地用于 DI 容器,我需要做的事情应该更简单。任何建议将不胜感激。这是我的示例代码:
以编程方式创建服务:
_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();
这就是我想要的服务方式(2a 或 2b)。2a. 带设置器的 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();
}