Readonly private interface - is this redundant?

I use IoC and DI for my project.

However, I was wondering if there is any good practice:

private readonly IMyService myservice;

as a field inside a class that is a consumer of a service. The field is specified in the constructor.

I am sure I saw it somewhere, and I took it. However, I also see:

private IMyService myservice;

and that seems to be enough. Is there any purpose to have a readonly field for the entered service interface? What are the benefits?

+5
source share
5 answers

I consider the use of the keyword a readonlycentral part of the correct implementation of constructor injection.

public class MyClass
{
    private readonly IMyService myservice;

    public MyClass(IMyService myservice)
    {
        if (myservice == null)
        {
            throw new ArgumentNullException("myservice");
        }
        this.myservice = myservice;
    }
}

readonly Guard . . .

+7

, , . readonly ( - ) . .

+9

A readonly , ctor. , . .

+4

readonly - , . .

void Method() {
  var marker = myservice.StartOperation();
  try {
    SomeOtherMethod();
  } finally {
    myservice.StopOperation(marker);
  }
}

, StartOperation StopOperation - , IMyService. myservice readonly, .

, readonly, SomeOtherMethod , . - reset myservice .

+2

readonly.

, readonly , " ". , .

, , , , , . , readonly, - .

In short, yes, it is good practice to declare something readonlyunless you change it after the object is constructed, as it will force all future authors to make this mistake.

+1
source

All Articles