SerialPort 的依赖注入 class

Dependency injection for SerialPort class

我想删除对 SerialPort class 的依赖,改用依赖注入。但是我不知道使用哪个接口。 SerialPort 实现 ICommand,但如果我使用此接口,我将无法使用 SerialPort 方法。

这是我的代码:

private readonly SerialPort _serialPort;

public CommandService(string comPort)
{
    _serialPort = new SerialPort(comPort, 9600, Parity.None, 8, StopBits.One) { Handshake = Handshake.None };
    try
    {
        _serialPort.Open();
    }
    catch (System.IO.FileNotFoundException)
    {
        throw new Exception($"Serialport { comPort } can't be found");
    }
    _serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceived);
}

public void Dispose()
{
    _serialPort.Close();
}

很遗憾,SerialPort 没有界面。如果你想将它与依赖注入一起使用,你将必须创建你自己的接口和一个实现它的 class 。这个 class 将只是 .NET SerialPort class:

的包装器
public class SerialPortWrapper : ISerialPortWrapper
{
    private readonly SerialPort port;

    public SerialPortWrapper(SerialPort port)
    {
       this.port = port;
    }

    public void Open()
    {
       port.Open();
    }

    public string ReadLine()
    {
       return port.ReadLine();
    }

    public void WriteLine(string line)
    {
       port.WriteLine();
    }
}

public interface ISerialPortWrapper
{
   void Open();
   string ReadLine();
   WriteLine(string line);
}

在您的 CommandService 中使用此接口 class:

private readonly ISerialPortWrapper _serialPort;

public CommandService(string comPort)
   : this(new SerialPortWrapper(new SerialPort(comPort, 9600, Parity.None, 8, StopBits.One) { Handshake = Handshake.None }))
{
}

public CommandService(ISerialPortWrapper serialPortWrapper)
{
    _serialPort = serialPortWrapper;

    try
    {
        _serialPort.Open();
    }
    catch (System.IO.FileNotFoundException)
    {
        throw new Exception($"Serialport { comPort } can't be found");
    }
}

为了简洁起见,我缩短了所有内容,但我希望你能理解。