Interface dependencies

When you create an interface, and know that you will have a dependency on another, do you create a part of the interface constructor?

In my case, I want to create

IClientReceiveRecorder, which I can provide to the client and receive all network traffic in a short test session. It will probably just contain a set of strings.

An IEvaluator that can receive all received messages and implement various things that we want to check. For example, I may have a specific evaluator that checks to see if all lines contain the letter "c".

I know that any IEvaluator will need IClientReceiveRecorder in order to receive the messages that it needs to evaluate.

So, I see several options. I'm doing something like

interface IEvaluator
{
    IEvaluator(IClientReceiveRecorder);

    void Evaluate();
} 

It does not compile, so I do not think so.

Maybe I'm something like

interface IEvaluator
{
    void Evaluate(IClientReceiveRecorder);
}

, IClientReceiveRecorder constuctor?

+4
4

, .

, IEvaluator IClientReceiveRecorder IEvaluator .

, , - :

interface IEvaluator
{
    IClientReceiveRecorder { get; set; }

    void Evaluate();
}

, .

+5

.

, . (). , ( ) , .

, , getter , . , , , , , , .

. (, .) , . , .

+4

IClientReceiveRecorder . , .

, - , IEvaluator. :

public IEvaluator
{
    void Evaluate();
}

, , . .

IClientReceiveRecorder IEvaluate :

public ConcreteEvaluator : IEvaluate
{
    private readonly IClientReceiveRecorder recorder;

    public ConcreteEvaluator(IClientReceiveRecorder recorder)
    {
        this.recorder = recorder;
    }

    public void Evaluate()
    {
        this.recorder.DoSomeRecording();
    }
}
0

, . , , , . , , , . , .

, .

, :

public class ClassThatDependsOnSomething
{
    private readonly IDependsOnThis _dependsOnThis;

    public ClassThatDependsOnSomething(IDependsOnThis dependsOnThis)
    {
        _dependsOnThis = dependsOnThis;
    }
}

, , , . - . , , , . .

, , IDependsOnThis ? ClassThatDependsOnSomething , ? .

. , DI , , . . , , . , . , , .

One of the key advantages of this is that since the class depends on the interfaces passed to its constructor, you can write unit tests for the class and pass "mocks" or "test double", really simple classes that implement interfaces and provide dummy answers to method calls. By controlling exactly what all the dependencies do, you can verify that your class behaves exactly as expected.

0
source

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


All Articles