Dependency Injection: I don’t understand where to start!

I have several articles about Injection Dependency Injection, and I see benefits, especially when it comes to unit testing. Units can loosen me up weakly, and addictions mock me.

The problem is, I just can't get where to start.

Consider this snippet below (heavily edited for the purpose of this post) the code I have. I create an instance of the Plc object from the main form and submit in communication mode via the Connect method.

It is difficult to verify in the present form because I cannot isolate Plc from CommsChannel to unit test. (Can I?)

The class depends on the use of the CommsChannel object, but I only pass the mode that is used to create this channel inside Plc itself. To use dependency injection, I really need to pass the already created CommsChannel (possibly via the ICommsChannel interface) to the Connect method or, perhaps, through the Plc constructor. Is it correct?

But then that would mean first creating a CommsChannel in my main form, and that also seems wrong, because it seems that everything will return to the base layer of the main form, where it all starts. Somehow it seems to me that I am missing an important piece of the puzzle.

Where do you start? You must create an instance somewhere, but I'm trying to figure out where it should be.

public class Plc()
{
    public bool Connect(CommsMode commsMode)
    {
        bool success = false;

        // Create new comms channel.
        this._commsChannel = this.GetCommsChannel(commsMode);

        // Attempt connection
        success = this._commsChannel.Connect();  

        return this._connected;
    }

    private CommsChannel GetCommsChannel(CommsMode mode)
    {
        CommsChannel channel;

        switch (mode)
        {
            case CommsMode.RS232:
                channel = new SerialCommsChannel(
                    SerialCommsSettings.Default.ComPort,
                    SerialCommsSettings.Default.BaudRate,
                    SerialCommsSettings.Default.DataBits,
                    SerialCommsSettings.Default.Parity,
                    SerialCommsSettings.Default.StopBits);
                break;

            case CommsMode.Tcp:
                channel = new TcpCommsChannel(
                    TCPCommsSettings.Default.IP_Address,
                    TCPCommsSettings.Default.Port);
                break;

            default:
                // Throw unknown comms channel exception.
        }

        return channel;
    }
}
+3
source share
2

, , / , .

factory, , , . , (, mock) , factory, , .

, ?

+1

Source: https://habr.com/ru/post/1783205/


All Articles