依赖注入确保你没有意外加载同一个模块两次

Dependency Injection Ensure that you have not accidentally loaded the same module twice

我正在使用 Ninject 进行依赖注入。我必须在构造函数中调用两个相同的 类。

public EsyonluAntennaManager(
    IModbusActuatorService dksEkbService1, IModbusActuatorService dksEkbService2)
{
   _dksEkbService1  = dksEkbService1;
   _dksEkbService2  = dksEkbService2;
}

IModbusActuatorService 和 ModbusActuatorManager 相互连接。

public ModbusActuatorManager(
    ISocketDeviceDal socketDeviceDal,
    IDataBaseErrorService dataBaseError,
    IDataBaseService dataBase,
    Code code)
{
    _socketDeviceDal = socketDeviceDal;
    _dataBaseError = dataBaseError;
    _dataBase = dataBase;
    _code = code;
}

ISocketDeviceDal 的构造函数不接受任何参数。 IDataBaseErrorServiceIDataBaseService 在构造函数中只有一个参数。

Bind<IDataBaseService>().To<DataBaseManager>()
    .WithConstructorArgument("path", _pathDbLog);
Bind<IDataBaseErrorService>().To<DataBaseErrorManager>()
    .WithConstructorArgument("path", _pathDbError);            
Bind<ISocketDeviceDal>().To<SocketDeviceDal>();
Bind<IModbusActuatorService>().To<ModbusActuatorManager>()
    .WithConstructorArgument("code", _code);

Bind<IKamciAntennaService>().To<KamciAntennaManager>();

我观察到Injection Ensure that you have not accidentally loaded the same module twice this error。我怎样才能做到这一点?如何注入 IKamciAntennaServiceKamciAntennaManager

public static T GetService<T>(
    string pathDbError, string pathDbLog, Code _code,Code _code1)
{
    var kernel = new StandardKernel(
        new DependecyInjection(pathDbError, pathDbLog, _code),
        new DependecyInjection(pathDbError, pathDbLog, _code1));
        
    return kernel.Get<T>();
}

已更新 我解决了这个问题。

        public EsyonluAntennaManager(
[Named("Local")]IModbusActuatorService dksEkbService1, 
[Named("Remote")] IModbusActuatorService dksEkbService2)
        {
           _dksEkbService1  = dksEkbService1;
           _dksEkbService2  = dksEkbService2;
        }

            Bind<IModbusActuatorService>().To<ModbusActuatorManager>().InTransientScope()
.Named("Remote").WithConstructorArgument("code", _codeRemote);

            Bind<IModbusActuatorService>().To<ModbusActuatorManager>().InTransientScope()
.Named("Local").WithConstructorArgument("code", _codeLocal);

这个问题的常见解决方案是采用工厂模式。

你创建一个工厂,它基于一些参数集,在运行时决定使用哪个 classes,然后你只是依赖注入那个工厂。

public interface IDksServiceFactory
{
   IDkservice ResolveDksService()//add some input paraameters?
} 

public DksServiceFactory : IDksServiceFactory
{
    public IDkservice ResolveDksService()
    {
        if()//something?
        {
            return  new DksEkbService1(); 
        }
        else
        {
            return new DksEkbService2(); 
        }
    }
}

public interface IDksService() // implement the interface for your "identical" services.
{
   
}

public class DksEkbService1 : IDksService
{
  
}

public class DksEkbService2 : IDksService
{
  
}

然后在您的服务中,您只需添加工厂,并使用构造函数中对象的“解析方法”来找到您需要的class。