I have a large public class which called Telescope
. I have created a new form (form1.cs
) and I want to call some of the public void that the class has.
I do something like this in the form to initialise the class
Telescope controls = new Telescope();
controls.CommandString("Gs#",true);
After that I can see the all the methods but it fails in the execution as the class is already initialized and there is an existing serial port connection ongoing, so it reports that there is no serial port connection.
Any help? How can I use the existing methods from the new form?
Telescope class is in Driver.cs
public string CommandString(string command, bool raw)
{
CheckConnected("CommandString");
serialPort.ClearBuffers();
serialPort.Transmit(command);
return serialPort.ReceiveTerminated("#");
}
When I use the CommandString in the Driver.cs (where the telescope class is) it works. It does not work from the form1.cs
I get an exception:
************** Exception Text **************
ASCOM.NotConnectedException: CommandString
Ideally you would be using some sort of IoC container and your class would implement an interface containing the bare minimal methods to interface with your serial connection. The IoC container would then manage the lifetime of the instance as a singleton and on every request to resolve the interface would pass you back the existing instance.
Since this may not be the case and since only a single instance can access the serial port, you could move these methods into a static class... But be careful, when you start sharing static methods, unexpected bugs can arise. Depending on how the code is structured, you would want only the serial connection to be static.
One example of how this could be implemented in a class:
private Lazy<SerialConnection> _serialConnection =new Lazy<SerialConnection>(StaticClass.GetStaticSerialConnection);
public SerialConnection MySerialConnection
{
get { return _serialConnection.Value; }
}