I have a DeviceManager
class which can handle different physical devices, and to say there are Classes A,B,C, which require a DeviceManager
instance as dependency. They should always use the same instance of DeviceManager
, however, at some point of time this DeviceManager
should create a new instance in order to wrap a different physical device. So in this case, in terms of maintainability and testability, should I use a static wrapper or dependency injection? I have two solutions, but don't know which is better, or maybe there is a way better solution.
Static Wrapper:
public static class DeviceService
{
static IDeviceManager _deviceManager;
public static void Handle() { _deviceManager.Handle(); }
public static void Reset()
{
_deviceManager = new DeviceManager();
}
}
ClassA,B,C instances then can use DeviceService.Handle()
and at some point of time to use DeviceService.Reset() to reassign a new instance.
Dependency Injection
public ClassA(IDeviceManager dm);
public ClassB(IDeviceManager dm);
public ClassC(IDeviceManager dm);
Assume that if I reassign the DeviceManager
, then I will also create new Class A,B,C instances.
Static wrapper is handy, and easy to manage the state, but it will become implicit dependency since it is not passed and referenced via parameters, would it be a pain in unit testing? And I need to call Reset() explicitly before I use/reuse it. Dependency Injection seems to have lower coupling and it is code agnostic, it can even handle using various DeviceManager
instances in the future, but my project has many classes and instances relying on DeviceManager
, I need to pass an instance to each of them additionally.
I still cannot decide on which one is better, and why. I need you helps.
Aucun commentaire:
Enregistrer un commentaire