Initialising configurable objects with dependency

2019-09-17 04:36发布

问题:

I am trying to find the best way to initialise device drivers (maintained by production staff). Configuration generally contains serial ports and other information which production staff may need to change if the underlying hardware for the device driver changes.

e.g.

using System.IO.Ports;

public class Scanner : IDriver
{
    public SerialPort SerialPort { get; private set; }
    public String Id { get; private set; }
    public String DisplayName { get; private set; }

    public Scanner(SerialPort serialPort, String id, String displayName)
    {
        SerialPort = serialPort;
        Id = id;
        DisplayName = displayName;
    }
}

public class TestMethod
{
    public Scanner MainScanner { get; private set; }
    public Scanner SecondaryScanner { get; private set; }

    public TestMethod (Scanner main, Scanner secondary)
    {
        MainScanner = main;
        SecondaryScanner = secondary;    
    }

}

How can I use a DI container and still make the configuration changeable at runtime? I would like to avoid using the XML configuration that comes with the DI containers as I expect the production staff to modify these (configuration) files often. A separate configuration file would be prefered.

A possible implementation of xml configuration

<DeviceDrivers>
    <Driver name="main" id="IX234" displayName="main scanner">
        <SerialPort name="serialPort" portName="COM8" baudRate="11560" parity="None" dataBits="8" stopBits="None">
    </Driver>
    <Driver name="secondary" id="IX2E3" displayName="secondary scanner">
        <SerialPort name="serialPort" portName="COM9" baudRate="11560" parity="None" dataBits="8" stopBits="None">
    </Driver>
</DeviceDrivers>

SerialPort itself need to be intialised from the configuration file.

Thanks

PS: I was considering Ninject, but not sure if I can pull this off.

回答1:

First of all I have not worked on Ninject but have some idea about Unity. Secondly, I hope I understood your problem correctly that you would want the mentioned XML configuration for DeviceDrivers to go as a separate config file to which production staff will not have access.

So for the said scenario I think you would have to have two different mapping for IDriver to Scanner (both should preferably be named, say, 'Main' and 'Secondary') and in both you can specify initialization values for instances of SerialPort as also mentioned in your XML config. All these configuration will be part of a separate file that will be loaded to Unity container. To see how to load container with configuration from multiple config files please refer to http://msdn.microsoft.com/en-in/library/ff660935(v=pandp.20).aspx.