A lot of people don’t seem to realize that setting readonly variables is indeed possible, it can only be done from inside the constructor:

public class SomeClass
{
   private readonly ISomeService _someService;
   private readonly ISomeOtherService _someOtherService;

   public SomeClass(ISomeService someService, ISomeOtherService someOtherService)
   {
      _someService = someService;
      _someOtherService = someOtherService;
   }
}

This is perfectly fine working code and I strongly recommend it. I use this a lot with dependency injection (DI). This makes sure that the injected instances cannot be overridden, because they can only be set in the constructor.
That’s why I really don’t like the requirement of a parameterless constructor in UserControls in WebForms. There is no possibility for injection, only resolving is possible.

The following two tabs change content below.
I'm a software developer from Utrecht. Interested in DDD, continuous delivery, new technologies & frameworks.

Latest posts by Vincent Keizer (see all)