Don't use reflection to instantiate driver

This commit is contained in:
2023-02-19 11:11:57 +01:00
parent 14b2e498ae
commit e144fb9788

View File

@@ -73,32 +73,14 @@ namespace TestApp
}
private static void UpdateDriverSettings(Settings settings) {
var dirverName = settings.ChargerDriver ?? Settings.DEFAULT_CHARGER_DRIVER;
var driverName = settings.ChargerDriver ?? Settings.DEFAULT_CHARGER_DRIVER;
var sampleDriverType = typeof(VestelEvc04);
var dirverNameSpace = sampleDriverType.Namespace;
var fullDriverTypeName = dirverNameSpace + "." + dirverName;
var driverType = sampleDriverType.Assembly.GetType(fullDriverTypeName);
if (driverType is null)
if (_Driver is null || !IsDriver(_Driver, driverName))
{
throw new ArgumentException($"Charger driver type '{dirverName}' not found!");
}
if (_Driver is null || !_Driver.GetType().Equals(driverType))
{
var newDriverConstructor = driverType.GetConstructor(Array.Empty<Type>());
if (newDriverConstructor is null) {
throw new InvalidOperationException($"Type {driverType} does not have a parameterless constructor!");
}
var newDriverObject = newDriverConstructor.Invoke(null, Array.Empty<object>());
if (newDriverObject is null)
var newDriver = CreateDriver(driverName);
if (newDriver is null)
{
throw new InvalidOperationException("Could not instantiate driver!");
}
if (newDriverObject is not IChargerDriver newDriver)
{
throw new InvalidOperationException("New driver does not implement IChargerDriver!");
throw new InvalidOperationException($"New driver {driverName} could not be found!");
}
if (_Driver is IDisposable disposable)
@@ -111,5 +93,21 @@ namespace TestApp
_Driver.HostAddress = settings.ChargerAddress ?? Settings.DEFAULT_CHARGER_ADDRESS;
_Driver.Port = settings.ChargerPort ?? Settings.DEFAULT_CHARGER_PORT;
}
private static bool IsDriver(IChargerDriver dirver, string name) {
return name switch
{
"VestelEvc04" => dirver is VestelEvc04,
_ => false
};
}
private static IChargerDriver? CreateDriver(string name) {
return name switch
{
"VestelEvc04" => new VestelEvc04(),
_ => null
};
}
}
}