刚刚使用依赖注入不久,很多还在摸索。请多指教😁。
我有一电机运动控制的类MotionControler,它继承于ModbusBase和IMotionControl。
ModbusBase 类是根据协议基本的读写操作,各个方法都有具体实现,因为长度原因不在此全部帖出。
IMotionControler是运动控制的基类。
///电机运动控制的类
public class MotionControler : ModbusBase, IMotionControl
{
public Axes axes;
//调用ModbusBase打开端口
public new bool OpenPort(string portName, byte slave)
{
return base.OpenPort(portName, slave);
}
//实现接口IMotionControl方法进行运动
public bool MoveAbs(int axis, int posPulse, double spd, double startSpd = 1, bool isWait = false, int interval = 50, int timeout = 10000)
{
MoveAbs(axis, posPulse);
return true;
}
/// <summary>
/// 提供Modbus协议的基本的操作,如打开、关闭端口,读写等。
/// </summary>
public class ModbusBase
{
public static int baudRate = 115200;
public static int dataBits = 8;//数据位
public static StopBits stopbits = StopBits.One;//停止位
public static Parity parity = Parity.None;//奇偶校验位
public static int readTimeout = 200;//超时时间
public delegate void PortMessage(string meg);
public PortMessage PortMsg;
public delegate void ErrorMessageDel(string msg);
public ErrorMessageDel ErrorMsg;
public SerialPort CurPort;
IModbusMaster master;
public ushort[] Mbs { get; set; }//数据格式
public int MaxAxis { get; set; } = 0;//最大轴数
//读取输入寄存器,输入寄存器为3区。一般一个寄存器占2个字节,而3区有20个寄存器。
public ushort[] ReadInputRegisters(int slave, ushort startAddr, ushort length)
{
lock (locker)
{
return master?.ReadInputRegisters((byte)slave, startAddr, length);
}
}
//搜索可用USB串口
public List<string> FindSerielPort() { }
public bool OpenPort(string portName, byte slave = 1)//连接端口 { }
// 写保持寄存器
public void WriteRegister(int slave,ushort startAddr,ushort value) { }
}
/// <summary>
/// 电机运动的控制
/// </summary>
public interface IMotionControl
{
bool ToOrigin(int axis, bool isWait = false,int interval=50,int timeout=10000);
//bool MoveAbs(int axis, double pos, double spd, double startSpd = 1, bool isWait = false,int interval=50,int timeout=10000);
bool MoveAbs(int axis, int posPulse, double spd, double startSpd = 1, bool isWait = false, int interval = 50, int timeout = 10000);
//bool MoveRel(int axis, double pos, double spd, double startSpd = 1, bool isWait = true, int interval = 50, int timeout = 10000);
bool MoveRel(int axis, int posPulse, double spd, double startSpd = 1, bool isWait = false, int interval = 50, int timeout = 10000);
void MoveVel(int axis, double spd, double startSpd = 1);
MotorState GetState(int axis);
bool PositionCheck(int axis, int posPulse, int interval = 50, int timeout = 10000);
bool PositionCheck(int[] axisArr, double[] posArr, int interval = 50, int timeout = 10000);
void Stop(int axis);
void Close();
}
依赖注入我使用的是微软的DependencyInjection:
var sc = new ServiceCollection();
sc.AddScoped(typeof(ITest), typeof(Test));
var sp = sc.BuildServiceProvider();
但是我在注入时却发现依赖注入只能有一个类或接口对应一个实现,无法使用类似于
sc.AddScoped(typeof(ModbusBase),typeof(IMotionControler), typeof(MotionControler ))
搜索了一下却没有发现有人这么做,是这种结构不合理吗?应该如何改呢?
在此先谢谢大家。