I am using IoC and DI for my project.
However I was wondering if it is good practise to have the following:
private readonly IMyService myservice;
as the field inside the class that is a consumer of the service. The field is set in the constructor.
I’m sure I’ve seen this somewhere and I’ve picked up on it.
However I also see:
private IMyService myservice;
and it seems to suffice. Is there any purpose to have a readonly field for the injected service interface? What are the advantages?
I consider use of the
readonlykeyword a central part of proper implementation of Constructor Injection.Neither the
readonlykeyword nor the Guard Clause are technically required to implement Constructor Injection. However, they both help strengthen the invariants of the class. This is what encapsulation is all about.