From e144fb9788392bd5e6545664eb63e2a57f3b3d54 Mon Sep 17 00:00:00 2001 From: Malte Bitter Date: Sun, 19 Feb 2023 11:11:57 +0100 Subject: [PATCH] Don't use reflection to instantiate driver --- TestApp/Program.cs | 44 +++++++++++++++++++++----------------------- 1 file changed, 21 insertions(+), 23 deletions(-) diff --git a/TestApp/Program.cs b/TestApp/Program.cs index 13b88d6..e29dc23 100644 --- a/TestApp/Program.cs +++ b/TestApp/Program.cs @@ -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()); - if (newDriverConstructor is null) { - throw new InvalidOperationException($"Type {driverType} does not have a parameterless constructor!"); - } - - var newDriverObject = newDriverConstructor.Invoke(null, Array.Empty()); - 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 + }; + } } }