I strongly suspect I shouldn’t be using a static factory method here, but for the mean time I am at a loss how to implement this. The following code gives a compile error on the line in CreateOpenPort that assigns _currentPort_DataReceived because that delegate method isn’t static. How can I resolve this, preferably using a non-static factory method?
public static SerialPortService CreateOpenPort(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
{
var service = new SerialPortService
{
_currentPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits)
};
service._currentPort.DataReceived += CurrentPortCharsReceived;
service._currentPort.Open();
return service;
}
void CurrentPortCharsReceived(object sender, SerialDataReceivedEventArgs e)
{
var port = (SerialPort) sender;
var chars = new char[port.BytesToRead];
var x = port.Read(chars, 0, chars.Length);
OnDataReceived(chars.ToString());
}
Hmm, static factory with a static handler is not so bad an idea although I will try avoiding them for the sake of unit tests.
Implement a singleton pattern if there is going it be only one instance in the AppDomain. That will be clean and working.